Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local variable still exists after function returns

I thought that once a function returns, all the local variables declared within (barring those with static keyword) are garbage collected. But when I am trying out the following code, it still prints the value after the function has returned. Can anybody explain why?

int *fun();
main() {
  int *p;
  p = fun();
  printf("%d",*p); //shouldn't print 5, for the variable no longer exists at this address
}
int *fun() {
  int q;
  q = 5;
  return(&q);
}
like image 294
SexyBeast Avatar asked Nov 30 '22 05:11

SexyBeast


2 Answers

There's no garbage collection in C. Once the scope of a variable cease to exist, accessing it in any means is illegal. What you see is UB(Undefined behaviour).

like image 192
P.P Avatar answered Dec 18 '22 06:12

P.P


It's undefined behavior, anything can happen, including appearing to work. The memory probably wasn't overwritten yet, but that doesn't mean you have the right to access it. Yet you did! I hope you're happy! :)

like image 31
Luchian Grigore Avatar answered Dec 18 '22 07:12

Luchian Grigore