_debug_malloc — Allocate memory

Format

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

Purpose

This is the debug version of malloc. Like malloc, it reserves a block of storage of size bytes from the default heap. _debug_malloc also sets all the memory it allocates to 0xAA, so you can easily locate instances where your program uses the data in the memory without initializing it first. In addition, _debug_malloc makes an implicit call to _heap_check, and stores the file name file and the line number line where the storage is allocated.

Return values

Returns a pointer to the reserved space. If not enough memory is available or if size is 0, returns NULL.

Examples

This example allocates 100 bytes of storage. It then attempts to write to storage that was not allocated. When _debug_malloc is called again, _heap_check detects the error, generates several messages, and stops the program.

/*   _debug_malloc.c  */
#include <stdlib.h>
#include <stdio.h>

int main(void)
{
   char *ptr1, *ptr2;

   if (NULL == (ptr1 = (char*)malloc(100))) {
      puts("Could not allocate memory block.");
      exit(EXIT_FAILURE);
   }
   *(ptr1 - 1) = 'a';        /* overwrites storage that was not allocated    */
   ptr2 = (char*)malloc(10); /* this call to malloc invokes _heap_check      */
   puts("_debug_malloc did not detect that a memory block was overwritten.");
   return 0;
}

Possible output is:

Header information of object 0x00073890 was overwritten at 0x0007388c.
The first eight bytes of the memory block (in hex) are: AAAAAAAAAAAAAAAA.
This memory block was (re)allocated at line number 8 in _debug_malloc.c.
Heap state was valid at line 8 of _debug_malloc.c.
Memory error detected at line 13 of _debug_malloc.c.