简体   繁体   中英

free malloc pointer locality issue

I am trying to implement a function set_it_free as shown below, but it would only play with the pointer locally, which does not do what I want, ie free and set to null for a pointer. Could you help me to modify my set_it_free to make it work?

int set_it_free(void* pointer, unsigned long level, char* message){
logMessage(level, message);
assert  (pointer != NULL);  //Never free a NULL pointer
free    (pointer);          //Free a malloc/calloc/realloc pointer
pointer = NULL;             //Set it to NULL for prevention
return 0;}

I would call it like this in main()

int* a = (int* )malloc(sizeof(int));
set_it_free(a);
int set_it_free(void** ppointer, unsigned long level, char* message)
{
    logMessage(level, message);
    assert  ( ppointer != NULL);  //Check valid parameter
    assert  (*ppointer != NULL);  //Never free a NULL pointer
    free    (*ppointer);          //Free a malloc/calloc/realloc pointer
    *ppointer = NULL;             //Set it to NULL for prevention
    return 0;
}

And example usage:

sometype* pMyVar = malloc(somesize);
set_it_free(&pMyVar, 5, "freeing myVar");

First of all, in C you should not cast the return values of functions returning void * (like malloc ). It can cause subtle runtime problems if you forget to include the correct header files.

Secondly, when you pass the pointer pointer to the function, the pointer itself is passed by value, meaning the pointer is copied and any assignment to the local copy inside set_it_free will be only local. This means the assignment to NULL inside the function is only done to the local pointer variable, the pointer a will still point to the now unallocated memory once the function returns.

For the last problem there are four ways of solving this: The first is to pass the pointer by reference (as in the answer by abelenky), the other is to return the new pointer (similar to what realloc does). The third way is to assign to a after the function call, either NULL or make it point to something else. The fourth way is to simply not use the variable a again.

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