Returning from a function that changes the address of a pointer, the address remains unchanged

I wrote a more complex program, but I narrowed down my problem to the following: Why does this program print garbage and not hzllo? I followed the values ​​and memory address of temp and p with a debugger, and it returns correctly from the foo function, and for some reason I don’t understand what is happening with the fingerprints.

void foo(char **str) { char temp[79]; strcpy_s(temp,79,*str); *(temp + 1) = 'z'; *str = temp; } void main() { char *p = (char*) malloc(79 * sizeof(char)); p = "hello"; foo(&p); printf("%s", p); } 
+4
source share
3 answers

Edit

 char temp[79]; # allocated on the stack, vanishes on return 

... before...

 static char temp[79]; # has a longer lifetime 

Also, you don't need malloc(3) .

+4
source

temp is a local variable that goes out of scope when exiting foo . So p is a dangling pointer, and your program has undefined behavior.

+4
source
 void foo(char **str) { // Bad: "temp" doesn't exist when the function returns char temp[79]; strcpy_s(temp,79,*str); *(temp + 1) = 'z'; *str = temp; } void main() { char *p = (char*) malloc(79 * sizeof(char)); p = "hello"; foo(&p); printf("%s", p); } 

This is better:

 void foo(char **str) { // This should change the pointer ... to something valid outside the function *str = (*str) + 1; } 
+1
source

All Articles