Cunit Testing free memory twice

149 Views Asked by At

excuse me i know that i should not free() twice a pointer, but how can i check if is not already free ? checking if null ? i don't know beacuse somebody told me that the free() comand doesn't write null in memory but simply deallocates the space! Help !! thanks a lot !

void buffer_destroy(buffer_t* buffer){
        if(buffer==NULL){
            return ;
        }

        int i;
        if(buffer->size>0){


        for(i=0;i<buffer->size;i++){
            msg_destroy_string(buffer->array_msg[i]);

        }

        }
        free(buffer->array_msg);
        free(buffer);

Actually I have in buffer.c a thread which launches a function and takes as argument the pointer called "buffer" .then i call a pthread_join on this thread but i don't know if automatically all arguments passed at his launch(in this case this pointer called "buffer") will be free(). because in a second moment It appeared an errror/exception on a double free() call, so probably a first free has been called automatically at the end of the thread beacuse i used "buffer" as argument ?

1

There are 1 best solutions below

0
On

Probably your logic has holes in it as Tony said. And the best answer would be to rework your code.

Please note, I'm not an expert in C, but if you can't change your code for whatever reason, then maybe you can try the following:
- add a variable "hasBeenFree = FALSE" (maybe global variable or a parameter to the function)
- and test it before you call free:

if (!hasBeenFree) {
   free(buffer);
   hasBeenFree = TRUE;
}

But I hope someone with more experience can answer you.

why tag "cunit" ?