0

What is the output of following C program And how is the output printed when all variables of fun() after closing got their memory de-allocated.

#include<stdio.h>
int * fun()
{
    int q = 10;
    int *p;
    p = &q;
    return p;
}    
int main()
{
    int *res;
    res= fun();
    printf("%d", *res);
    return 0;
}

I expected the pointer res to point to null

Blaze
  • 16,736
  • 2
  • 25
  • 44
David
  • 1
  • 4
    This is undefined behavior. – tkausl Jun 25 '19 at 12:56
  • When you do `printf("%d", *res);`, where is the `int` that you're trying to print? On which line was it made? – Blaze Jun 25 '19 at 12:57
  • Memory being deallocated is not the same as setting a pointer to it to `null`. – Scott Hunter Jun 25 '19 at 12:57
  • There are several different mechanisms for memory allocation/deallocation. Furthermore, even when memory is deallocated (that is, when you call `free` on memory that you've dynamically allocated with `malloc`, or when you return from a function so that its local memory or "stack frame" is deallocated), the key is that *the deallocated memory is typically not immediately destroyed or even made unavailable*. It's still there, at the same address, so if you have a pointer to it you can still see it -- but it might change at any time if some other part of your code allocates and starts using it.. – Steve Summit Jun 25 '19 at 14:24

1 Answers1

0

You are returning a pointer to an address on the stack. A reasonable compiler will give you a warning like this:

"warning C4172: returning address of local variable or temporary: q"

But basically the behavior is undefined and also depends on your level of optimization.

SirNobbyNobbs
  • 486
  • 4
  • 9