0
#include<stdio.h>
 
int *func(int * ptr){
    int a = 12;
    int *c = &a;
    return c; // here it returns the pointer by storing the address of local variable   
}

int main()
{
    int *ptr = NULL;
    ptr= func(ptr); // here the address is stored but the local variable gets destroyed
    printf("the value is %d\n",*ptr); // So how can it print the value 12 here if local variable gets destroyed or did I miss something?    
    return 0;
}

Output

The valus is 12

But how it is possible because when it returns the address by storing it in the pointer the variable get destroy so ptr becomes dangle but it still gives output 12.

Collin
  • 11,977
  • 2
  • 46
  • 60
anonymous
  • 19
  • 5
  • It does become dangling, but the memory it points to is still there (sometimes). What you invoke here is undefined behavior and may stop working at any time. – 500 - Internal Server Error Apr 18 '22 at 17:51
  • As a general principle, if you're reading about C and you see phrases like "this gets destroyed", "this crashes your program", etc, you should mentally translate to "this *might* get destroyed", "this *might* crash your program", etc. It's a threat, not a promise. More formally, most such things result in [undefined behavior](https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior) which *might* misbehave in any way you can imagine, or in ways that you can't imagine. – Nate Eldredge Apr 19 '22 at 14:58

1 Answers1

0

Because nothing actually enforces that the memory location your previous stack frame was in gets overwritten or destroyed. The memory where your pointer was declared still belongs to your application, and is probably sitting there untouched.

What you've invoked here is undefined behavior which may do unpredictable things, including work when it's not "supposed" to.

Collin
  • 11,977
  • 2
  • 46
  • 60