Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return from a function which changes pointer address, address stays the same

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);
}
like image 332
Steinfeld Avatar asked Jan 14 '23 12:01

Steinfeld


2 Answers

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).

like image 107
DigitalRoss Avatar answered Jan 23 '23 02:01

DigitalRoss


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.

like image 44
Kerrek SB Avatar answered Jan 23 '23 02:01

Kerrek SB