I was trying to learn about dangling pointers, so I made a quick test including inner local scope, within the main function, and a pointer defined outside that inner local scope. Inside of it i'm defining and initializing local variable, and I'm assigning it's address as value of the pointer.
Here is the example:
#include <stdio.h>
int main()
{
int *ptr = NULL;
//Start of local scope
{
int a = 10;
ptr = &a;
printf("Address of a: %p\nValue of ptr: %p\n", &a, ptr);
}
//End of local scope
printf("\nDereferenced value of ptr: %d", *ptr);
return 0;
}
The output is:
Address of a: 0x7ffcacf6146c
Value of ptr: 0x7ffcacf6146c
Dereferenced value of ptr: 10
I was expecting some segmentation fault error or undefined behaviour, since the local scope is left, the local variable - terminated, and so I expected it's value to be erased.
Indeed - the variable is terminated, it's impossible to access it outside the scope, since it no longer exists. But the value stored in it continues to exist on the same address. After the local scope is left isn't it supposed the value to be erased alongside the variable, to which is assigned to? Isn't the memory location, which is occupied by the variable, cleansed from it's contents, after the end of the local scope is reached?
Isn't it supposed that this memory location, once freed, to be returned at OS disposal, thus making it inaccessible from the program? Or it remains to program's disposal until program termination occurs, and execution control is reverted back to OS?
One more code example. Let's modify the above example, and just define (without initializing) another variable of the same type, but this time outside of the scope, after it. On all tests I did - it occupied the same memory location, and even more - is being initialized with the same value, just because occupies the memory location on which the value was stored through the previous variable.
#include <stdio.h>
int main()
{
int *ptr = NULL;
//Start of local scope
{
int a = 10;
ptr = &a;
printf("Address of a: %p\nValue of ptr: %p\n", &a, ptr);
}
//End of local scope
int b;
printf("\nAddress of b: %p\nValue of b: %d\n", &b, b);
printf("\nDereferenced value of ptr: %d", *ptr);
return 0;
}
Output is:
Address of a: 0x7fff5f9faecc
Value of ptr: 0x7fff5f9faecc
Address of b: 0x7fff5f9faecc
Value of b: 10
Dereferenced value of ptr: 10