函数调用后指针的值仍然可用?

Nig*_*ife 1 c pointers

#include <stdio.h>
//needed so we can use the built in function strcpy
#include <string.h>
int main()
{
char* foo()
    {
        char* test="Hello";
        printf("value of test: %p\n",test);
        return test;

    }


    //why does this work? is test off the stack, but Hello in mem is still there?
    work=foo();
    printf("value of work after work has been initalized by foo(): %p\n",work);
    printf("%s\n",work);
}
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,'work = foo()',作品我注意到'test'和'work'的值是相同的.这意味着它们指向内存中的相同点,但在函数调用'test'之后超出范围并且不允许访问.为什么不允许访问'test',但其值/内存位置是?我假设由于在函数调用后离开堆栈,不允许访问'test'?我是新手,所以如果我的术语或任何内容都关闭,请纠正我.

Iha*_*imi 6

嵌套函数不是标准的c,它是gcc 的扩展,所以你的代码不会总是编译,并且由于gcc扩展它确实有效.

这是真的原因与嵌套函数无关,如果执行以下操作,您将观察到完全相同的行为

#include <stdio.h>

char *foo()
{
    char* test="Hello";
    printf("value of test: %p\n",test);
    return test;

}

int main()
{
    // why does this work? is test off the stack, but Hello in mem is still there?
    char *work = foo();

    printf("value of work after work has been initalized by foo(): %p\n",work);
    printf("%s\n",work);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

该函数foo()将地址返回到静态字符串,该字符串在程序的生命周期内保留.

我是你创建一个数组,你将地址返回到一个不可能的局部变量

#include <stdio.h>

int main()
{

    char *foo()
    {
        char test[] = "Hello";

        printf("value of test: %p\n", test);
        printf("value of foo: %p\n", foo);

        return test;
    }

    // why does this work? is test off the stack, but Hello in mem is still there?
    char *work = foo();

    printf("value of work after work has been initalized by foo(): %p\n",work);
    printf("%s\n",work);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译器会在最后一种情况下发出警告,并且printf("%s\n",work);会打印垃圾,虽然printf("value of work after work has been initalized by foo(): %p\n",work);会打印相同的地址,数据会被堆栈框架破坏foo.