c++ - 返回指针 c

标签 c++ c function pointers methods

<分区>

Possible Duplicate:
Pointer to local variable
Can a local variable's memory be accessed outside its scope?

我有一个有趣的问题。我有一个返回指针的读取函数:

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

现在,我调用这个函数来为我拥有的一些变量分配信息:

char * s;
//Some code to specify where to read from.
s = myReadFunc();

这会产生我预期的结果。

但是,当我这样做时:

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

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

所以我尝试了一些替代代码:

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

这段代码产生了我预期的结果(s1 有来自一个位置的数据,而 s2 有来自另一个位置的数据)。

所以,我的问题是,为什么后面的代码有效,而上面的代码却没有? 我猜我的函数以某种方式为这两个变量设置了别名,并且由于它指向这两个变量,所以每次调用时都会重新分配这两个变量。有谁了解这种行为的全部原因?

最佳答案

您的 readFunc 函数没有按您预期的那样工作。

您正在返回一个指向数组的指针,该数组仅在函数主体的范围内。当函数退出时,数组超出范围,稍后尝试访问该内存会调用未定义的行为。它可能看起来在某些情况下有效,但实际上是不正确的。

相反,在 readFunc 中,使用 newmalloc 在堆上分配数组:

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

关于c++ - 返回指针 c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11799434/

相关文章:

c++ - 如何在函数中更新 C++ 字符串?

c - 如何让 typedef 结构跨多个文件文件工作?错误 : invalid use of undefined type 'struct data'

R: "apply"语句用于计算多列中非 NA 值的数量之和

c++ - C++ 中的迭代器开始/结束与 :collection

c++ - 我如何在 Qt 中从 Internet 下载文件?

.net - 从 native C 调用 .NET 托管代码

c++ - auto 作为函数参数

matlab - 初始化函数时出现意外的MATLAB运算符错误

c++ - 在c++中添加两个字符串

c - 外部变量未按预期运行