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

标签 c

#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/

相关文章:

c - 在示例中,为什么 float 转换为 int 打印不同的结果?

C语言中使用结构体和指针创建学生记录

c - 根据Index交换数组的值

c - 如何在 C 中使用 libevdev 生成键盘输入

c - C 中的引用传递

c - 链接器忽略库链接

c - 函数原型(prototype)中的顶级 volatile 或 restrict 是否重要?

c++ - 类 C 结构中自动字段重新排序的方法

c - C语言中如何求重复小数

c++ - 使用 OpenGL 添加远处的雾?