【发布时间】:2016-03-21 15:31:57
【问题描述】:
我目前正在尝试释放分配的内存,但是这样做会导致程序崩溃。我是 C 和一般编程的新手,如果能在问题和任何其他可能源于我的经验不足的问题上获得帮助,我会很高兴。
Pool* allocatePool(int x);
void freePool(Pool* pool);
void store(Pool* pool, int offset, int size, void *object);
typedef struct _POOL
{
int size;
void* memory;
} Pool;
int main()
{
printf("enter the number of bytes you want to allocate//>\n");
int x;
Pool* p;
scanf("%d", &x);
p=allocatePool(x);
freePool(p);
return 0;
}
/* Allocate a memory pool of size n bytes from system memory (i.e., via malloc()) and return a pointer to the filled data Pool structure */
Pool* allocatePool(int x)
{
static Pool p;
p.size = x;
p.memory = malloc(x);
printf("%p\n", &p);
return &p;//return the address of the Pool
}
/* Free a memory pool allocated through allocatePool(int) */
void freePool(Pool* pool)
{
free(pool);
printf("%p\n", &pool);
}
【问题讨论】:
-
您必须
free与您分配的内存相同。你malloc到p.memory,但是你free(&p),这根本不是分配在堆上的内存,而是静态对象的地址。 -
永远不会是
free()函数导致程序崩溃。这是您的代码中的一个错误导致程序崩溃。 -
@SergeyA Never 有点强。这有点像说你永远不会被闪电击中。当然这不太可能,但并不是说没有 malloc/free somewhere 的任何错误实现。
-
@Cubic,
-fpedantic:) -
关于这种错误:这里使用系统的工具来帮助你。 Microsoft 的调试模式下的 Visual Studio 会以相当丰富的信息使您的程序崩溃。在 Linux 中使用“valgrind”运行您的程序,这将报告错误的 free() 调用。
标签: c