I’m experimenting with the stack in C to tests some things and learn more in the language.
I know that a function has a stack frame created by moving the rsp/rbp pointer.
What I don’t understand is that when I’m creating a char[] in a function, exiting from it, and accessing the pointer in another stack frame, it seems like the data has disapeared, but the compiled code doesn’t seems to have anything that clears it.
Example C code:
#include <string.h>
#include <stdio.h>
char *save_ptr = 0;
void print_ptr(char *ptr)
{
char increase_stack[200];
printf("%pn", increase_stack); // Prints 0x1fff0000a0
printf("%sn", (char *) 0x1fff0000a0); // Prints nothing
printf("%sn", increase_stack); // Prints nothing
printf("%sn", save_ptr); // Prints nothing
}
char *create_str(void)
{
char mstring[200];
save_ptr = mstring;
memmove(mstring, "1234567890", 11);
printf("%pn", mstring); // Prints 0x1fff0000a0
printf("%sn", mstring); // Prints 1234567890
return mstring;
}
int main(void)
{
char *test = create_str();
// test is 0 beacause of GCC
printf("%pn", test); // Prints 0
test = save_ptr;
printf("%pn", test); // Prints 0x1fff0000a0
print_ptr(test);
}
So, the thing I don’t understand is that, even if the address is style 0x1fff0000a0
, it seems like the data has disapeared between the call, enven tho the address is the same and I didn’t wrote anything to it.
Compiled also doesn’t seems to write to this address (see compiled code at: https://godbolt.org/z/jdrov6Exz).
For compilation I used the following flags: -g -Og -fno-isolate-erroneous-paths-attribute -fno-isolate-erroneous-paths-attribute
Can someone explain why I don’t see “1234567890” writen by print_ptr() ?