C/C++: A small tip for freeing dynamic memory


Taking into account the behavior of the free() function, it is a good practice to set your pointer to NULL right after you free it.

By doing so, you can rest assured that in case you accidentally call free() more than one times on the same variable (with no reallocation or reassignment in between), then no bad side-effects will happen (besides any logical issues that your code might be dealing with).

You can include free() from malloc.h and it will have the following signature extern void free(void *__ptr);.

Description of operation:

Free a block allocated by malloc, realloc or calloc.
The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc(), or realloc().  Otherwise, if free(ptr) has  already been called before, undefined behavior occurs.  If ptr is NULL, no operation is performed.

Working examples:


#include <stdio.h>
#include <malloc.h>

int main()
{
  printf("Hello, World!\n");

  void * c = malloc (sizeof(char) * 10);

  free(c);
  c = NULL;
  free(c);

  return 0;
}


#include <iostream>

int main()
{
  std::cout << "Hello, World!" << std::endl;

  void * c = malloc (sizeof(char) * 10);

  free(c);
  c = NULL;
  free(c);

  return 0;
}

This post is also available in: Greek

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.