返回指针c

Cod*_*tti 4 c c++ methods pointers function

可能重复:
指向局部变量的指针
可以在其范围之外访问局部变量的内存吗?

我有一个有趣的问题.我有一个返回指针的read函数:

char * myReadFunc() {   
    char r [10];
    //some code that reads data into r.
    return r;
}
Run Code Online (Sandbox Code Playgroud)

现在,我调用此函数将信息分配给我的一些变量:

char * s;
//Some code to specify where to read from.
s = myReadFunc();
Run Code Online (Sandbox Code Playgroud)

这会产生我想要的结果.

但是,当我这样做时:

char * s1;
char * s2;
//Some code to specify where to read from.
s1 = myReadFunc();
//Some code to change the read location.
s2 = myReadFunc();
Run Code Online (Sandbox Code Playgroud)

我得到一些奇怪的结果.两者的数据相同,并且始终来自第二个指定的读取位置.

所以我尝试了一些备用代码:

char * s1;
char * s2;
//Some code to specify where to read from.
char r [10];
//some code that reads data into r. IDENTICAL to myReadFunc().
s1 = r;
//Some code to change the read location.
s2 = myReadFunc();
Run Code Online (Sandbox Code Playgroud)

此代码按我的意图生成结果(s1包含来自一个位置的s2数据,并且具有来自另一个位置的数据).

所以,我的问题是,为什么后面的代码工作,但它上面的代码没有?我的猜测是,我的函数以某种方式对两个变量都有别名,因为它指向两者,所以每次调用它都会重新分配.有没有人理解这种行为的全部原因?

pb2*_*b2q 8

您的readFunc功能无法正常工作.

您将返回一个指向数组的指针,该数组仅位于函数体中的范围内.当函数退出时,数组超出范围,稍后尝试访问该内存会调用未定义的行为.它似乎在某些情况下有效但不正确.

相反,在readFunc,使用new或在堆上分配数组malloc:

// it is the responsibility of the caller to delete[] the
//    returned buffer, but prefer to use e.g. shared_ptr
char *myReadFunc()
{
    char *r = new char[BUFFER_SIZE];
    //some code that reads data into r.
    return r;
}
Run Code Online (Sandbox Code Playgroud)