gpt4 book ai didi

C:包含动态分配成员的结构的范围?

转载 作者:太空宇宙 更新时间:2023-11-04 01:24:47 25 4
gpt4 key购买 nike

我有一个结构和一个返回 Foo 实例的函数,定义如下:

struct Foo
{
int a;
int* b;
};

struct Foo makeFoo(int a, int bSize)
{
struct Foo foo;
foo.a = a;
foo.b = malloc(sizeof(int) * bSize);
for (int i = 0; i < bSize; ++i)
foo.b[i] = i;

return foo;
}

最初,我认为foo 是一个局部变量,当makeFoo 返回时它就会消失,但是从这个问题Is it safe to return a struct in C or C++? ,我知道这样做是安全的。

现在我的问题是什么时候收集foo 的内存?我必须先释放它的 b 成员吗?

假设我这样使用 makeFoo:

void barFunc()
{
struct Foo foo = makeFoo(3, 10);

printf("Foo.a = %d;\nFoo.b = [", foo.a);
for (int i = 0; i < 10; ++i)
printf("%d, ", foo.b[i]);

printf("\n");
}

void main(int argc, char* argv)
{
barFunc();
}

barFunc 返回并且我回到 main 时,是否收集了 foo 的内存?或者我必须在 barFunc 的末尾调用 free(foo.b) 吗?

最佳答案

Initially, I thought foo is a local variable and it'll be gone when makeFoo returns, but from this question Is it safe to return a struct in C or C++?, I know that it's safe to do so.

确实意识到本地foo确实不见了?按值返回 struct 只是将其内容复制到调用者提供的实例中。(*)

但是,当然,内容包括一个指向您使用malloc() 分配的内存的指针。所以它必须在 free() 之后。

(*) 这可能对于小型结构来说是个好主意,具体取决于您的需要,但请始终记住复制了全部内容——这绝对不是您想要的大型结构结构。

关于C:包含动态分配成员的结构的范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33225908/

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