我有一个名为 exam 的全局变量,其类型为 struct Exam:
typedef struct
{
Question* phead;
}Exam;
Exam exam;
在函数中,我为指针 phead 分配空间:
int initExam()
{
exam.phead = malloc(sizeof(Question*));
exam.phead = NULL;
return 1;
}
在一个单独的函数中,我尝试释放此内存:
void CleanUp()
{
unsigned int i = 0;
Question* currentQuestion = exam.phead;
while (currentQuestion != NULL) {
// some other code
}
exam.phead = NULL;
}
我还在我的函数中尝试了以下操作:
free(exam.phead);
我的问题是它似乎没有释放由 malloc 分配的内存。我希望 CleanUp() 释放由 exam.phead 分配的内存,并且我无法更改函数签名或将 free() 调用移至另一个函数。我做错了什么吗?我对 C 编程相当陌生。谢谢!
最佳答案
你从一开始就有内存泄漏:
int initExam()
{
exam.phead = malloc(sizeof(Question*));//assign address of allocated memory
exam.phead = NULL;//reassign member, to a NULL-pointer
return 1;
}
exam.phead
成员被分配了您分配的内存的地址,只是在之后变成了空指针。空指针可以安全地释放
,但它不会做任何事情。
同时,malloc
的内存将保持分配状态,但您没有指向它的指针,因此无法管理它。您无法释放
内存,也无法使用它。我认为 NULL 赋值是尝试将内存初始化为“干净”值。有很多方法可以做到这一点,我稍后会介绍。
无论如何,因为phead
为NULL,所以以下语句:
Question* currentQuestion = exam.phead;//is the same as currentQuestion = NULL;
while (currentQuestion != NULL) //is the same as while(0)
完全没有道理。
要初始化新分配的内存,请使用memset
或calloc
。后者将分配的内存块初始化为零,memset
可以做到这一点(calloc
与调用malloc
+ 基本相同memset
),但允许您初始化为您喜欢的任何值:
char *foo = calloc(100, sizeof *foo);// or calloc(100, 1);
//is the same as writing:
char *bar = malloc(100);
memset(bar, '\0', 100);
关于c - 如何在单独的函数中释放 malloc 的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25769417/