gpt4 book ai didi

可以覆盖返回的结构吗?

转载 作者:行者123 更新时间:2023-12-05 01:28:33 24 4
gpt4 key购买 nike

我有一个由某个函数返回的结构:

struct Abc {
char *a;
int b;
};

static struct Abc foo() {
struct Abc mystruct;
mystruct.a = "asdf";
mystruct.b = 1;

return mystruct;
}

如果我调用struct Abc new_abc = foo();new_abc中存储的结构是否有可能被程序覆盖?

如果我理解正确的话,mystruct 是一个自动变量,它在范围内是局部的。因此,引用可能会悬空,因此可以被覆盖。

最佳答案

If I call struct Abc new_abc = foo();, is it possible for the struct stored in new_abc to be overwritten by the program?

是的,new_abc 只是另一个变量。它可以被程序(mer)所希望的覆盖。

If I understand correctly, mystruct is an automatic variable which is local in scope. Thus the reference might be left dangling and hence can be overwritten.

您返回的不是局部变量的地址,而是值。返回结构变量在功能上与返回本地 intchar 相同。这里没有悬挂指针。


编辑:

如评论中所述:

“它会被为其他东西分配内存的程序覆盖吗”

答案是否定的。您正在返回值并将其存储在变量中。当然,如果你创建了太多的局部变量,你可能会面临堆栈溢出,但是为自动局部变量(用于存储返回值)分配的内存将不会被索回,除非它发生超出范围。

换句话说,一旦局部变量的值从函数返回并存储在调用者的另一个变量中,函数中的局部变量不再需要存在才能访问调用者中存储的值。

关于可以覆盖返回的结构吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55573049/

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