gpt4 book ai didi

c - 如果我将指针保留在函数中,则C标准是否将函数的返回结构保留在堆栈中?

转载 作者:行者123 更新时间:2023-12-03 15:25:58 24 4
gpt4 key购买 nike

采取这个可疑的代码。

struct X {
int arr[1];
float something_else;
};

struct X get_x(int first)
{
struct X ret = { .arr = { first } };
return ret;
}

int main(int argc, char **argv) {
int *p = get_x(argc+50).arr;

return *p;
}
get_x返回一个 struct X
我只对它的成员 arr感兴趣。如果我只想要 arr,为什么还要为整个结构制作局部变量?
但是..该代码正确吗?
在所示示例中,C标准是否知道将 get_x的返回值保留在堆栈上,直到调用堆栈帧结束,因为我正在用指针偷看它的内部?

最佳答案

标准不允许您在做什么。
从该函数返回的结构具有临时生命周期,该生命周期在其使用的表达式之外结束。因此,在初始化p之后,它指向一个生命周期已经结束且其值不确定的对象。然后在以下语句中尝试取消引用p(现在是不确定的)会触发undefined behavior
这在C standard的6.2.4p8节中有记录:

A non-lvalue expression with structure or union type, wherethe structure or union contains a member with array type(including, recursively, members of all contained structures andunions) refers to an object with automatic storage duration andtemporary lifetime. Its lifetime begins when the expression is evaluated and its initial value is the value of the expression.
Its lifetime ends when the evaluation of the containing fullexpression or full declarator ends. Any attempt to modify anobject with temporary lifetime results in undefined behavior.


在第6.2.4p2节中指定了对象的 生命周期以及在其生命周期结束时指向该对象的指针发生了什么:

The lifetime of an object is the portion of programexecution during which storage is guaranteed to be reservedfor it. An object exists, has a constant address, and retainsits last-stored value throughout its lifetime. If an objectis referred to outside of its lifetime, the behavior isundefined. The value of a pointer becomes indeterminate when theobject it points to (or just past) reaches the end of its lifetime


如果要将函数的返回值分配给 struct X的实例,则可以安全地访问该实例的 arr成员。

关于c - 如果我将指针保留在函数中,则C标准是否将函数的返回结构保留在堆栈中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66810468/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com