Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C : Passing auto variable by reference

I came across a piece of code which is working fine as of now,but in my opinion its undefined behavior and might introduce a bug in future.

Pseudo code :

void OpertateLoad(int load_id)
{
   int value = 0;

   /* code to calculate value */

   SetLoadRequest(load_id,&value);

   /*some processing  not involving value**/

}

void SetLoadRequest(int load_id, int* value)
{
   /**some processing**/
   LoadsArray[load_id] = *value; 
   /**some processing**/ 
}

In my understanding C compiler will not guarantee where Auto variables will be stored. It could be stack/register(if available and suitable for processing).

I am suspecting that if compiler decides to store value onto general purpose register then, SetLoadRequest function might refer to wrong data.

Am I getting it right?or I am overthinking it?

I am using IARARM compiler for ARM CORTEX M-4 processor.

----------:EDIT:----------

Answers Summarize that " Compiler will ensure that data is persisted between the calls, no matter where the variable is stored ".

Just want to confirm : Is this behavior also true 'if a function is returning the address of local auto variable and caller is de-referencing it?'.

If NO then is there anything in C standard which guarantees the behavior in both cases? Or As I stated earlier its undefined behavior?

like image 725
Vagish Avatar asked Dec 07 '22 16:12

Vagish


1 Answers

You are overthinking it. The compiler knows that, if value is in a register, that it must be stored to memory before passing a pointer to that memory to SetLoadRequest.

More generally, don't think about stack and registers at all. The language says there's a variable (without saying how it's implemented), and that you can take its address and use that in another function to refer to the variable. So you can!

The language also says that local variables cease to exist when leaving a block, so this permission does not extend to returning pointers to local variables (which causes undefined behavior if the caller does anything at all with the pointer).

like image 169
Davis Herring Avatar answered Dec 26 '22 19:12

Davis Herring