What are the possible behaviors of the program below?
I have tried to allocate and use memory on stack, and print the memory block pointed by p, output are characters of '\0'.
I known technically it is not available when the function returns.
However, why not the program crash, or print some random garbage?
#include <cstring>
#include <cstdio>
#include <cstdlib> //malloc
char* getStackMemory(){
char mem[10];
char* p = mem;
return p;
}
int main(){
char* p = getStackMemory();
strcpy(p, "Hello!");
printf("%s\n", p);
for(int i = 0; i<10; i++){
printf("%c\n", p[i]);
}
return 0;
}