現在割り当てられているメモリを解放しようとしていますが、そうするとプログラムがクラッシュします。私はCやプログラミング全般を初めて熟知しており、経験の浅さから生じる可能性がある問題やその他の問題の助けを受けることができます。Free()関数がプログラムをクラッシュさせます
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'必要があります。あなたは 'p.memory'に' malloc'を入れますが、ヒープにはメモリは割り当てられていませんが、静的オブジェクトのアドレスは 'free(&p)'です。 –
これはプログラムをクラッシュさせる 'free()'関数ではありません。あなたのコードのバグで、プログラムがクラッシュします。 – SergeyA
@ SergeyA _Never_は少し強いです。あなたが雷に襲われることは決してないと言っているようなものです。確かにそれほど有望ではありませんが、malloc/free _どこかにバグのある実装はありません。 – Cubic