I wrote a more complex program but I have narrowed down my problem to the following one: Why is this program printing down junk and not hzllo? I have followed the values and memory address of temp and p with the debugger and it returns from the foo function correctly and for a reason I don't understand prints junk.
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);
}
Change
char temp[79]; # allocated on the stack, vanishes on return
...to...
static char temp[79]; # has a longer lifetime
Also, you don't need the malloc(3)
.
temp
is a local variable, which goes out of scope when you exit foo
. Thus p
is a dangling pointer and your program has undefined behaviour.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With