简体   繁体   中英

How to free NULL pointer after using malloc

For example, i have the code below for calculate the size of pointer (like an array in this case):

#include <stdio.h>
#include <stdlib.h>

int **ptr;
void init() {
    ptr = malloc(sizeof(int *)*5);
    if(!ptr){
        printf("cannot malloc, \n");
        return;
    }
    for(int i =0; i < 5; i++) {
        ptr[i] = malloc(sizeof(int));
        if(!ptr[i]){
            printf("cannot malloc, ptr[%d]\n", i);
            return;
        }
    }
    ptr[4] = NULL;
}

int main(void) {
    init();
    int count = 0;
    while(ptr[count] != NULL) {
        count++;
    }
    printf("size of ptr = %d\n", count);
}

IDEA:

Add NULL pointer at the and of array in init() function, then using while loop to calculate the size by increasing the count until meet the NULL pointer. Is it a bad idea?

The question;

As i know, for free(pointer) function, if pointer is NULL, nothing occurs. So, How to free ptr[4] ?

I try to free this pointer:

    for(int i =0; i < 5; i++) {
        free(ptr[i]);
    }
    free(ptr);

Then verify by Valgrind

==2957== 4 bytes in 1 blocks are definitely lost in loss record 1 of 1
==2957==    at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==2957==    by 0x108775: init (test2.c:12)
==2957==    by 0x1087E1: main (test2.c:22)
==2957== 
==2957== LEAK SUMMARY:
==2957==    definitely lost: 4 bytes in 1 blocks
==2957==    indirectly lost: 0 bytes in 0 blocks
==2957==      possibly lost: 0 bytes in 0 blocks
==2957==    still reachable: 0 bytes in 0 blocks
==2957==         suppressed: 0 bytes in 0 blocks

One thing i can try is to use realloc (i know realloc(PTR, 0) is not equivalent to free(PTR) ):

ptr[4] = realloc(ptr[4], 0);

But there are still the memory-leaks when i test by Valgrind.

You malloc some memory, store that value in ptr[4] , then overwrite ptr[4] with NULL . This is where your memory leak occurs. Nothing you do after that can recover the lost memory.

You'll want to stop your loop at 4 (instead of 5).

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