[英]Why do I get an "invalid pointer" when freeing a pointer to a struct in C
我刚刚尝试重新学习 C 中的结构,所以我制作了这个测试代码。 在其中,我已经能够成功地创建指向 C 中的结构的指针。 如果没有最后的两个自由语句,代码就可以正常工作。
但是,当我在代码末尾添加自由语句时,我收到一个错误指针无效。 我以为我正确地为指向结构的指针分配了 memory 并释放它。 我也只释放了所有指针。
我将得到一个 output:(仅当代码中包含自由语句时才添加最后两行)
5
5 10 0x7ffc7ee52e04 20
55 40 0x7ffc7ee52e08 2000
free(): invalid pointer
Aborted (core dumped)
我该如何解决这个问题,为什么? (这是我的第一个堆栈溢出帖子,如果有什么我做错了或者有什么不清楚的地方,很抱歉)
谢谢!
代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
struct point_struct {
int length;
int width;
int *height;
};
struct point_struct house; // Ignore house struct, everything here worked fine.
house.length = 5;
printf("%i\n", house.length);
house.width = 10;
int var = 20;
house.height = &var;
printf("%i %i %p %i\n", house.length, house.width, house.height, *house.height);
struct point_struct *plane = NULL; // Declare plane pointer to struct
plane = malloc(sizeof(struct point_struct)); // Allocate memory for pointer to plane struct
if (plane == NULL) {
printf("MEMORY ALLOCATION FAILED plane\n");
exit(1);
}
int pLength = 55; // Values to be stored in plane
int pWidth = 40;
int pHeight = 2000;
(*plane).length = 55; // Both (*). and -> dereference AND
plane->width = 40; // get an element of a struct
int pValue = 2000;
(*plane).height = malloc(sizeof(int)); // Allocates memory for height in pointer to plane struct
if ((*plane).height == NULL) {
free(plane);
printf("ALLOCATE MEMORY FAILURE, plane->length\n");
exit(1);
}
plane->height = &pHeight;
// prints values inside of plane including an address
printf("%i %i %p %i\n", plane->length, plane->width, plane->height, *(plane->height));
free(plane->height); // Adding these 2 lines is supposed to free the struct.
free(plane); // However, they cause the error
return 0;
}
当您调用free(plane->height)
时,它指向局部变量pHeight
。 您只能使用通过malloc
系列中的某些东西return
的指针来调用free
。
int pHeight = 2000;
(*plane).height = malloc(sizeof(int));
if ((*plane).height == NULL) {
free(plane);
printf("ALLOCATE MEMORY FAILURE, plane->length\n");
exit(1);
}
plane->height = &pHeight;
free(plane->height)
您为int
分配 memory 并使height
指向此 memory。
然后,您将height
指向pHeight
,这是一个具有自动存储持续时间的变量。 结果导致 memory 泄漏,因为您malloc()
'd 的 memory 现在丢失了。
然后在height
上调用free()
,它指向不是来自malloc()
、 calloc()
或realloc()
的 memory ,因此在其上使用free()
是无效的。
free()
手册页说:
void free(void *ptr);
The free() function frees the memory
space pointed to by ptr, which must
have been returned by a previous call
to malloc(), calloc() or realloc().
您为int
类型的 object 动态分配了 memory
(*plane).height = malloc(sizeof(int)); // Allocates memory for height in pointer to plane struct
但是随后您重新分配了指针的值
plane->height = &pHeight;
现在指向局部变量pHeight
int pHeight = 2000;
因此代码产生了 memory 泄漏,因为动态分配的 memory 的地址丢失了。 并且您可能不会为指向局部变量的指针free
调用 function。
相反,你应该写
*plane->height = pHeight;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.