I'm trying to come up with an example for a dangling pointer in C, but the code I came up with produces results that don't exactly display what I'm expecting.
#include <stdio.h>
int* dangling_ptr();
int main(void)
{
    int* ptr = dangling_ptr();
    printf("%d\n", *ptr); // outputs 5 to the console
    return 0;
}
int* dangling_ptr()
{
    int x = 5;
    int* x_ptr = &x;
    return x_ptr;
}
I was expecting some garbage integer value to be sitting in the memory returned, but de-referencing and printing the value displays 5 to the screen.
I know that the memory address returned by dangling_ptr() is not valid anymore, but it's clear that the memory still hasn't been overwritten.  This brings up two questions.
- Is my understanding of dangling pointers here wrong? The memory should now be invalid, correct? 
- If I am correct in my understanding, why hasn't the OS reclaimed that memory and made it invalid? Why is the value 5 still sitting there? 
 
    