#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
。所以你必须分别释放s1
和s2
。要么:
free(s1);
free(s2);
或者:
free(s1->next);
free(s1);
在第二种情况下,语句的顺序很重要,因为如果 s1
被释放,您将无法访问 s1
引用的对象。
C11 (n1570), § 7.22.3.3 The
free
function
Thefree
function causes the space pointed to byptr
to be deallocated, that is, made available for further allocation.
关于c - 关于 C' stdlib.h 中 free() 可能的链式 react ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12997449/