Search code examples
c++linuxmemorymallocfree

Memory deallocation in linux c++?


In my application I allocated memory for my variable (unsigned char*) using malloc(), when try to deallocate that memory in destructor I use this condition to avoid double corruption.

unsigned char *wsqData;
wsqData= (unsigned  char *)malloc( 10000*sizeof( unsigned char));

in my destructor

  if(wsqData!=NULL)
  {
      free(wsqData);
      wsqData=NULL;
  } 

now the problem is when I freed the memory before my destructor,this "if condition " could not working properly ,it once again try to free that variable it cause double corruption error. What is the problem in this scenario?


Solution

  • Calling free on the memory doesn't automatically set your pointer to NULL, so your condition is pointless. You need to set wsqData to NULL wherever you free it.

    Of course the condition is pointless anyway, since calling free on a NULL pointer is guaranteed to be safe.