_debug_free — Free allocated memory

Format

#include <stdlib.h>    /* also in <malloc.h> */
void _debug_free(void *ptr, const char *file, size_t line);

Purpose

This is the debug version of free. Like free, it frees the block of memory pointed to by ptr. _debug_free also sets each block of freed memory to 0xFB, so you can easily locate instances where your program uses the data in freed memory. In addition, _debug_free makes an implicit call to the _heap_check function, and stores the file name file and the line number line where the memory is freed.

Because _debug_free always checks the type of heap from which the memory was allocated, you can use this function to free memory blocks allocated by the regular, heap-specific, or debug versions of the memory management functions. However, if the memory was not allocated by the memory management functions, or was previously freed, _debug_free generates an error message and the program ends.

Return values

There is no return value.

Examples

This example reserves two blocks, one of 10 bytes and the other of 20 bytes. It then frees the first block and attempts to overwrite the freed storage. When _debug_free is called a second time, _heap_check detects the error, prints out several messages, and stops the program.

/*  _debug_free.c  */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
   char *ptr1, *ptr2;
   if (NULL == (ptr1 = (char*)malloc(10)) || NULL == (ptr2 = (char*)malloc(20))) {
      puts("Could not allocate memory block.");
      exit(EXIT_FAILURE);
   }
   free(ptr1);
   memset(ptr1, 'a', 5);      /* overwrites storage that has been freed       */
   free(ptr2);                 /* this call to free invokes _heap_check       */
   puts("_debug_free did not detect that a freed memory block was overwritten.");
   return 0;
}

The output is similar to:

Free heap was overwritten at 0x00073890.
Heap state was valid at line 12 of _debug_free.c.
Memory error detected at line 14 of _debug_free.c.