gpt4 book ai didi

C - 释放 'inherited' 结构

转载 作者:行者123 更新时间:2023-12-01 15:05:28 27 4
gpt4 key购买 nike

在下面的代码中,释放Dairy也会释放Yogurt吗?
据我所知,两者都指向同一个地址。

此外,这种编码风格是否是一种不好的做法?假设我只保留指向 Dairy 的指针并间接释放 YogurtCheese

#include <stdlib.h>

typedef struct {
int calcium;
int protein;
} Dairy;

typedef struct {
Dairy dairy;
int sugar;
int color;
} Yogurt;

int main () {
Yogurt* yogurt = malloc(sizeof(Yogurt));

Dairy* dairy = &yogurt->dairy;

free(dairy); // Will this free yogurt?
}

最佳答案

是的,行为定义明确。

根据 C 标准,您需要将完全相同的地址传递给释放函数 free正如 malloc 返回的那样或其他分配函数。

引用:

7.22.3.3 The free function

Synopsis:

§1 #include <stdlib.h> void free(void *ptr);

Description:

§2 The free function causes the space pointed to by ptr to be deallocated, that is, madeavailable for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by a memory managementfunction, or if the space has been deallocated by a call to free or realloc, thebehavior is undefined.

因此,在这种情况下,当且仅当指向结构的指针与指向它的第一个成员的指针相同时,才能保证行为被明确定义。
这由以下标准保证:

6.7.2.1 结构和 union 说明符
§15

Within a structure object, the non-bit-field members and the units in which bit-fieldsreside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamedpadding within a structure object, but not at its beginning.

关于C - 释放 'inherited' 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9189339/

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