可以覆盖返回的结构吗?

标签 c struct scope return-value

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

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/

相关文章:

c - 避免在 C 程序中使用 main(入口点)

c - 返回 mallocatted 数组的大小

objective-c - 运算符 'overloading' 等同于 C/Objective-C 中的#define

c# - 变量范围对性能的影响? (C#)

swift - 如果 Swift 'guard' 语句必须退出作用域,那么作用域的定义是什么?

C:指针分配错误

C - 结构错误的动态数组

尽管函数和结构是包含的头文件的成员,但 C 错误 : implicit declaration of function and storage size isn't known,

c - 包含 scanf 和 file 的结构

c++ - 内联友元函数的范围是什么?