Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When C 'deallocates' local stack variable? [duplicate]

Local variables exists at least (and at most) inside functions. However, what happens to block-scope variables outside block but it the same function, could I keep and use their address? Is this code valid?

#include <stdio.h>

int main()
{
   char *f;
   if (1)
   {
       char q[] = "123";
       f = q;   
   }

   printf ("%s\n", f);   
   return 0;
}

In fact neither gcc -ansi -pedantic nor valgrind complain on it, but could I use it cross-platform and cross-compiler? Seems to me no, but what tool could show me the error?

P.S. Should I use static after all? It could be appropriate solution, but it seems to me not a thread safe one?

like image 960
Nick Avatar asked Jan 04 '23 03:01

Nick


1 Answers

No you cannot. Variables with automatic storage duration have their lifetime set to the enclosing block. What you end up with is a dangling reference, and using that is undefined behavior.

[C11 §6.2.4 ¶2]

The lifetime of an object is the portion of program execution during which storage is guaranteed to be reserved for it. An object exists, has a constant address,33) and retains its last-stored value throughout its lifetime.34) If an object is referred to outside of its lifetime, the behavior is undefined. The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime.

[C11 §6.2.4 ¶6]

For such an object (with automatic storage duration) that does not have a variable length array type, its lifetime extends from entry into the block with which it is associated until execution of that block ends in any way.

like image 119
StoryTeller - Unslander Monica Avatar answered Jan 18 '23 22:01

StoryTeller - Unslander Monica