【问题标题】:returning pointers c [duplicate]返回指针c [重复]
【发布时间】:2012-08-01 17:18:41
【问题描述】:

可能重复:
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 有来自另一个位置的数据)。

所以,我的问题是,为什么后面的代码有效,而上面的代码却没有? 我的猜测是,我的函数不知何故被这两个变量取别名,并且由于它指向这两个变量,因此每次调用它时都会重新分配这两个变量。有人了解这种行为的全部原因吗?

【问题讨论】:

标签: c++ c function pointers methods


【解决方案1】:

您的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;
}

【讨论】:

  • 为什么是malloc,而不是new
  • @Andrew 啊,我假设是 C 标签,将编辑
  • 我觉得有义务通知 OP,虽然此答案中提供的功能有效且具有指导意义,但这是一个坏主意。不应让调用者负责释放内存。也许在 C 中这是可以接受的。在 C++ 中,它不是。我们还有其他更好的选择。
【解决方案2】:

您尝试执行的操作无法定义任何行为,因为您尝试访问生命周期已结束的数组所指向的内存。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-11
    • 1970-01-01
    • 2012-10-02
    • 2016-03-16
    • 1970-01-01
    • 2013-01-12
    • 2018-03-23
    • 2017-08-08
    相关资源
    最近更新 更多