我有一个名为examination的全局变量,其类型为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成员被分配了您分配的内存的地址,只是在此之后成为空指针。空指针可以安全地free进行,但是它什么也没做。
同时,malloc的内存将保持分配状态,但是您没有指向它的指针,因此无法管理它。您不能free内存,也不能使用它。我认为NULL分配是尝试将内存初始化为“干净”值。有很多方法可以解决,稍后我将介绍。

无论如何,由于phead为NULL,因此以下语句:

Question* currentQuestion = exam.phead;//is the same as currentQuestion = NULL;
while (currentQuestion != NULL) //is the same as while(0)


完全没有道理。

要初始化新分配的内存,请使用memsetcalloc。后者将分配的内存块初始化为零,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 - 如何释放在单独函数中分配的指针?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25769417/

10-08 22:43
查看更多