Home > Back-end >  Using local variables with functions that take pointers in FreeRTOS
Using local variables with functions that take pointers in FreeRTOS

Time:04-22

I need some explanation/clarification about using local variables in FreeRTOS when I need to pass them to another functions as pointers.

For example I have some function that modifies data under pointer 'data'.

void modify_data(int * data){
    *data = 10; 
}

Can I use it like this?

void some_function(void){
    int d;  // local variable
    modify_data(&d);
}

Or maybe I should make global variable?

int d;
void some_function(void){
    modify_data(&d);
}

Or static variable?

void some_function(void){
    static int d;
    modify_data(&d);
}

My question in general is:

How to use (or replace) local variables with functions that take pointers in FreeRTOS?

Edit:

At this moment my understanding of this is:

  • local variables within a function have no use if I want to pass their pointers to another function (or do anything with pointers pointing these variables) because task switching can cause change of memory location where local variable is stored

  • I have to declare variables as static or global if I want to do anything with their pointers

  • this is a bit annoying, because a lot of variables in my big program must be declared globally and passing pointers to global data makes no sense except for the readability of the code

I'm using FreeRTOS 10.2.1, CMSIS 1.02 and code runs on STM32 microcontroller.

CodePudding user response:

For starters this statement

*data = (*data)  ; 

invokes undefined behavior.

As for your question then to change a variable within a function you need to pass it to the function by reference that is indirectly through a pointer to it. For example

void f( int *px )
{
    *px = 10;
}

void g( void )
{
    static int x;
    f( &x );
}

CodePudding user response:

Depends on what you want to do. If you want to use d outside of that function you need to define it as a global, if you are only gonna use it inside the function declare it as local.

  • Related