从更改指针地址的函数返回,地址保持不变

时间:2013-01-15 23:54:35

标签: c visual-studio

我写了一个更复杂的程序,但我已将我的问题缩小到以下问题: 为什么这个程序打印垃圾而不是hzllo?我已经使用调试器跟踪了temp和p的值和内存地址,并且它正确地从foo函数返回,并且由于某种原因我不理解print 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);
}

3 个答案:

答案 0 :(得分:4)

temp是一个局部变量,当您退出foo时,该变量超出范围。因此p是一个悬空指针,你的程序有不确定的行为。

答案 1 :(得分:4)

更改

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

...到...

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

此外,您不需要malloc(3)

答案 2 :(得分:1)

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

这样更好:

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