【问题标题】:How would I free a pointer malloc'd in a separate function?如何在单独的函数中释放指针 malloc'd?
【发布时间】:2014-09-10 15:30:15
【问题描述】:

我有一个名为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 编程相当陌生。谢谢!

【问题讨论】:

  • 您在将exam.phead 分配到initExam 之后立即将其设置为NULL。这是直接的内存泄漏。
  • 你没有释放指针,你释放了它们指向的东西。

标签: c pointers visual-studio-2012 malloc free


【解决方案1】:

您从一开始就有内存泄漏:

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'd,但它不任何事情。
同时,malloc'ed 内存将保持分配状态,但您没有指向它的指针,因此无法管理它。你不能free内存,也不能使用它。我认为NULL 赋值是尝试将内存初始化为 "clean" 值。有一些方法可以解决这个问题,我稍后会介绍。

不管怎样,因为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);

【讨论】:

    【解决方案2】:

    在使用malloc 分配内存后,您正在将initExam 中的exam.phead 设置为NULLfree() 不使用 NULL 指针做任何事情,所以你正在泄漏内存。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-14
      • 2021-12-03
      • 2012-08-07
      • 2022-09-27
      • 1970-01-01
      • 2017-01-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多