Steinfeld
Steinfeld

Reputation: 689

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);
}

Upvotes: 4

Views: 1042

Answers (3)

paulsm4
paulsm4

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

DigitalRoss
DigitalRoss

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

Kerrek SB
Kerrek SB

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

Related Questions