【发布时间】:2016-08-04 13:47:31
【问题描述】:
是否可以在指向结构的第一个成员的指针上调用 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);
}
【问题讨论】:
-
@user71815 我认为没有必要,最好编译和检查。 (然后让我们知道)
-
你为什么要写这样的代码?
-
这绝对是一件奇怪的事情。我永远不会写这样的代码。为什么不直接释放原始指针,而不是尝试从结构成员的地址推断它?
-
@TomKarzes 是的 - 当有人在开始时推入另一件事会发生什么?
-
"如果已经问过这个问题,请删除它。"不会。几年后其他人可能会发现它很有用。
标签: c struct malloc padding free