gpt4 book ai didi

c - 关于 C' stdlib.h 中 free() 可能的链式 react

转载 作者:太空宇宙 更新时间:2023-11-04 05:43:07 26 4
gpt4 key购买 nike

#include <stdlib.h>

struct strt;
typedef struct {
int i;
struct strt *next;
} strt;

strt *s1 = malloc(sizeof(strt));
strt *s2=s1->next = malloc(sizeof(strt));

free(s1);

现在,free(s1) 是只释放 s1 指向的 block 还是释放 s1 s1->next/s2 指向的 block ?

我知道这一定是一个被问过一千遍的问题,但是我无法在搜索引擎上描述这一点,也无法我发现在 free() 函数的文档中直接提到了同样的问题。

最佳答案

每个 malloc 应该有一个 free。所以你必须分别释放s1s2。要么:

free(s1);
free(s2);

或者:

free(s1->next);
free(s1);

在第二种情况下,语句的顺序很重要,因为如果 s1 被释放,您将无法访问 s1 引用的对象。

C11 (n1570), § 7.22.3.3 The free function
The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation.

关于c - 关于 C' stdlib.h 中 free() 可能的链式 react ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12997449/

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