_debug_ucalloc — Reserve and initialize memory from a user-created heap

Format

#include <umalloc.h>
void *_debug_ucalloc(Heap_t heap, size_t num, size_t size, const char *file,
                     size_t line);

Purpose

This is the debug version of _ucalloc. Like _ucalloc, it allocates memory from the heap you specify for an array of num elements, each of length size bytes. It then initializes all bits of each element to 0. In addition, _debug_ucalloc makes an implicit call to _uheap_check, and stores the name of the file file and the line number line where the storage is allocated.

If the heap does not have enough memory for the request, _debug_ucalloc calls the heap-expanding function that you specify when you create the heap with _ucreate.

Note: Passing _debug_ucalloc a heap that is not valid results in undefined behavior.

Return values

Returns a pointer to the reserved space. If size or num was specified as zero, or if your heap-expanding function cannot provide enough memory, returns NULL.

Examples

This example creates a user heap and allocates memory from it with _debug_ucalloc. It then attempts to write to memory that was not allocated. When _debug_free is called, _uheap_check detects the error, generates several messages, and stops the program.

/*  _debug_ucalloc.c  */
#include <stdlib.h>
#include <stdio.h>
#include <umalloc.h>
#include <string.h>
int main(void)
{
   Heap_t  myheap;
   char    *ptr;
   /* Use default heap as user heap */
   myheap = _udefault(NULL);
   if (NULL == (ptr = (char*)_ucalloc(myheap, 100, 1))) {
      puts("Cannot allocate memory from user heap.");
      exit(EXIT_FAILURE);
   }
   memset(ptr, 'x', 105);   /* Overwrites storage that was not allocated */
   free(ptr);
   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: 7878787878787878.
This memory block was (re)allocated at line number 14 in _debug_ucalloc.c.
Heap state was valid at line 14 of _debug_ucalloc.c.
Memory error detected at line 19 of _debug_ucalloc.c.