Reputation: 689
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);
}
Upvotes: 4
Views: 1042
Reputation: 121659
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;
}
Upvotes: 1
Reputation: 146073
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)
.
Upvotes: 4
Reputation: 477060
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.
Upvotes: 4