gpt4 book ai didi

c - 使用指向第一个成员的指针调用 free 是否有效?

转载 作者:太空狗 更新时间:2023-10-29 16:44:25 25 4
gpt4 key购买 nike

可以在指向结构第一个成员的指针上调用 free 吗(结构是与 malloc 相关的结构)?我原则上知道指针无论如何都指向正确的东西......

struct s {int x;};
//in main
struct s* test;
test = (struct s*) malloc(sizeof(*test));
int* test2;
test2 = &(test->x);
free(test2); //is this okay??

此外,如果 int x 被替换为结构,答案会改变吗?

更新:我为什么要编写这样的代码?

struct s {int x;};
struct sx1 {struct s test; int y;}; //extending struct s
struct sx2 {struct s test; int z;}; //another
// ** some functions to keep track of the number of references to each variable of type struct s
int release(struct s* ptr){
//if the number of references to *ptr is 0 call free on ptr
}
int main(){
struct sx1* test1;
struct sx2* test2;
test1 = (sx1*) malloc(sizeof(*sx1));
test2 = (sx2*) malloc(sizeof(*sx2));
//code that changes the number of references to test1 and test2, calling functions defined in **
release(test1);
release(test2);
}

最佳答案

是的,没关系。

6.7.2.1

  1. 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 astructure object, suitably converted, points to its initial member (or if that member is abit-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.

这意味着这是定义的:

struct s {int x;};
struct s* test;
test = (struct s*) malloc(sizeof(*test));
int* p = &(test->x);
free(p);

关于c - 使用指向第一个成员的指针调用 free 是否有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36598832/

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