use*_*815 11 c malloc free struct padding
是否可以在指向结构的第一个成员的指针上调用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??
Run Code Online (Sandbox Code Playgroud)
此外,如果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);
}
Run Code Online (Sandbox Code Playgroud)
是的,这没关系.
6.7.2.1
- 在结构对象中,非位字段成员和位字段所在的单元具有按声明顺序增加的地址.指向适当转换的结构对象的指针指向其初始成员(或者如果该成员是位字段,则指向它所在的单元),反之亦然.结构对象中可能存在未命名的填充,但不是在其开头.
这意味着这是定义的:
struct s {int x;};
struct s* test;
test = (struct s*) malloc(sizeof(*test));
int* p = &(test->x);
free(p);
Run Code Online (Sandbox Code Playgroud)
根据C11标准,章节§6.7.2.1
[...]结构对象中可能有未命名的填充,但不是在其开头.
这意味着在结构的开头不能有任何填充.因此,第一个成员将具有与结构变量相同的地址.
free()需要一个先前由malloc()家人或家人返回的指针.
在您的情况下,您传递的是malloc()返回的相同地址.所以,你很高兴.