我目前正试图释放分配的内存,但这样做会导致程序崩溃。我对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',但是你释放了(&p)',它根本不是内存分配的堆,而是一个静态对象的地址。 –
它永远不会是导致程序崩溃的'free()'函数。它是导致程序崩溃的代码中的一个错误。 – SergeyA
@SergeyA_Never_有点强。这有点像说你永远不会被闪电击中。确定它不太可能,但它不像malloc/free _somewhere_有任何错误的实现。 – Cubic