c - 如何在单独的函数中释放 malloc 的指针?

标签 c pointers visual-studio-2012 malloc free

我有一个名为 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)

完全没有道理。

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

相关文章:

c# - 从对象中读取类数据?

c++ - 有没有办法在编写 C++ 代码时理解 Visual Studio 2012 提示?

c - 分配var = 0.0时程序退出;

c - 如果有许多具有相同参数的函数,是否应该使用宏来避免多次输入参数?

c - printf() 中的 % 在此代码片段中如何工作?(相对于 Turboc2 编译器)

c++ - 将 map<string, int> 转换为 void* 并返回并获取 key

svn - 如何配置TortoiseSVN以使用Visual Studio 2012进行差异?

c - 将 const char* 传递给函数时丢失数据

c++ - 了解 C++ 中的指针初始化行为

c# - C# 的 C++ 代码帮助