简体   繁体   中英

Why even after memory de allocation from stack the output is not garbage?

#include<stdio.h>
char* call();
void hello();
void hello2();

int main()
{
  char * p=call();
  hello();
  hello2();

 printf("%c\n",*p);
 return 0;
}

void hello()
{
   printf("HELLO\n");
}

void hello2()
{
   printf("hello2\n");
}

char* call()
{
   char  a = 's';
   char *b = &a;
   return b;
}

The above program gives the following output:

HELLO

hello2

s

what I know is when I am calling call() function from main then a stack frame will be allocated in stack and when call() function returns address then memory will be de-allocated but when I am trying to print the value stored in variable 'a' then the output is correct .The confusion I have is that even after de-allocation why the output is correct ?

You should not consider your output to be correct. It has the appearance of being correct, but you should consider that to be coincidence. You're observing undefined behavior , and that theoretically means that anything can happen, such as producing the value you expect, formatting your hard drive, or (as some people like to say) causing demons to fly out of your nose. The pointer does point to garbage; while it might seem to point to something valid, you have no guarantee that the behavior you observe will be reproducible in the future.


As to why the output might appear to be "correct", memory is typically not automatically cleared when deallocated. Doing so is extra work and is typically not something that is done by default. Another possibility is that since you're accessing a "wild" pointer, you get back a random value that coincidentally matches the value you originally assigned. (As they say, a broken clock is correct twice per day.)

The stack is preallocated and reserved for the current thread of execution. Just because something is deallocated, it doesn't mean that it automatically gets smeared. The data will most likely be replaced when a subsequent call to other functions are made.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM