#include <stdlib.h> /* also in <malloc.h> */ void *_debug_calloc(size_t num, size_t size, const char *file, size_t line);
This is the debug version of calloc. Like calloc, it allocates memory from the default heap for an array of num elements, each of length size bytes. It then initializes all bits of each element to 0. In addition, _debug_calloc makes an implicit call to _heap_check, and stores the name of the file file and the line number line where the storage is allocated.
Returns a pointer to the reserved space. If not enough memory is available, or if num or size is 0, returns NULL.
This example reserves storage of 100 bytes. It then attempts to write to storage that was not allocated. When _debug_calloc is called again, _heap_check detects the error, generates several messages, and stops the program.
/* _debug_calloc.c */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
char *ptr1, *ptr2;
if (NULL == (ptr1 = (char*)calloc(1, 100))) {
puts("Could not allocate memory block.");
exit(EXIT_FAILURE);
}
memset(ptr1, 'a', 105); /* overwrites storage that was not allocated */
ptr2 = (char*)calloc(2, 20); /* this call to calloc invokes _heap_check */
puts("_debug_calloc did not detect that a memory block was overwritten.");
return 0;
}
The output is similar to:
End of allocated object 0x00073890 was overwritten at 0x000738f4. The first eight bytes of the memory block (in hex) are: 6161616161616161. This memory block was (re)allocated at line number 9 in _debug_calloc.c. Heap state was valid at line 9 of _debug_calloc.c. Memory error detected at line 14 of _debug_calloc.c.