#include <umalloc.h> void *_debug_umalloc(Heap_t heap, size_t size, const char *file, size_t line);
This is the debug version of _umalloc. Like _umalloc, it reserves storage space from the heap you specify for a block of size bytes. _debug_umalloc 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_umalloc 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_umalloc calls the heap-expanding function that you specify when you create the heap with _ucreate.
Returns a pointer to the reserved space. If size was specified as zero, or your heap-expanding function cannot provide enough memory, returns NULL.
This example creates a heap myheap and uses _debug_umalloc to allocate 100 bytes from it. It then attempts to overwrite storage that was not allocated. The call to _debug_free invokes _uheap_check, which detects the error, generates messages, and ends the program.
/* _debug_umalloc.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*)_umalloc(myheap, 100))) {
puts("Cannot allocate memory from user heap.\n");
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_umalloc.c. Heap state was valid at line 14 of _debug_umalloc.c. Memory error detected at line 19 of _debug_umalloc.c.