简体   繁体   中英

How would I free a pointer malloc'd in a separate function?

I have a global variable called exam which is of type struct Exam:

typedef struct 
{
    Question* phead;
}Exam;

Exam exam;

In a function I malloc space for the pointer phead:

int initExam()
{
    exam.phead = malloc(sizeof(Question*));
    exam.phead = NULL;

    return 1;
}

In a separate function I try to free this memory:

void CleanUp()
{
    unsigned int i = 0;
    Question* currentQuestion = exam.phead;

    while (currentQuestion != NULL) {
        // some other code
    }
    exam.phead = NULL;
}

I have also tried the following inside my function:

free(exam.phead);

My issue is it does not seem to free the memory allocated by malloc. I would like CleanUp() to free up the memory allocated by exam.phead and I cannot change the function signatures or move the free() calls to another function. Is there something I'm doing wrong? I'm fairly new to C programming. Thanks!

You have a memory leak, right from the off:

int initExam()
{
    exam.phead = malloc(sizeof(Question*));//assign address of allocated memory
    exam.phead = NULL;//reassign member, to a NULL-pointer

    return 1;
}

the exam.phead member is assigned the address of the memory you allocated, only to become a null-pointer right after. A null pointer can be free 'd safely, but it doesn't do anything.
Meanwhile, the malloc 'ed memory will stay allocated, but you have no pointer to it, and therefore cannot manage it. You can't free the memory, nor can you use it. I take it the NULL assignment is an attempt to initialize the memory to a "clean" value. There are ways to to this, which I'll get to in a moment.

Anyway, because phead is NULL, the following statements:

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

don't make sense, at all.

To initialize newly allocated memory, either use memset , or calloc . The latter initializes the allocated block of memory to zero, memset can do this do ( calloc is basically the same as calling malloc + memset ), but allows you to initialize to any value you like:

char *foo = calloc(100, sizeof *foo);// or calloc(100, 1);
//is the same as writing:
char *bar = malloc(100);
memset(bar, '\0', 100);

You're setting exam.phead in initExam to NULL right after you allocate memory with malloc . free() doesn't do anything with a NULL pointer so you're leaking memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM