Returning the address of a local variable is illegal. Some compilers detects this and instead of returning the actual address of the local variable, the compiler makes the function return a NULL pointer.
That is likely what happens in your first example. So when you dereference the pointer (aka the return value), the program crashes.
In the second example your compiler doesn't detect that the return value is an address of a local variable so the address is actually returned. And when you dereference the pointer (aka the return value), it just happens that the "old" value from the function is still present at that address.
In both cases your code has undefined behavior. What actually happens depends on your specific system.
Try printing the return values like:
int* func1(void){
int a = 10;
printf("In func1: Address of a is %p\n", &a);
return &a;
}
int* func2(void){
int a = 10;
printf("In func2: Address of a is %p\n", &a);
int* b = &a;
return b;
}
int main(void){
int* h = func1();
printf("Value returned by func1: %p \n", (void*)h);
int* hh = func2();
printf("Value returned by func2: %p \n", (void*)hh);
return 0;
}
My output:
In func1: Address of a is 0x7ffdc3bc0a6c
Value returned by func1: (nil)
In func2: Address of a is 0x7ffdc3bc0a6c
Value returned by func2: 0x7ffdc3bc0a6c
Why does the value of a local variable sometimes persist after the function ends?
Most systems (if not all) use a pre-allocated memory block - called a stack - during function calls. A stack pointer tells how much of that memory block that is currently being used. When a function is called, the stack pointer is changed to use a little more of that memory block (i.e. to store function local variables and possibly other stuff). When the function returns the stack pointer is changed back to the old value again. But it's no required that the memory used by the function is changed in any way. So if you after a function return (illegally) access the stack memory that the function was using, it's likely that you will see the old values still being present.