next up previous
Next: Virtual memory files Up: Analysis Previous: Analysis

Overloading allocators in C

The easiest way to map allocators to new functions in C is to use the C preprocessor. The following piece of code does the job:

#define malloc(s)        xmemory_malloc(s)
#define calloc(n,s)      xmemory_calloc(n,s)
#define strdup(s)        xmemory_strdup(s)
#define free(p)          xmemory_free(p)

To include extended memory handling in an application, it is sufficient to include the memory header file to re-direct all memory allocations to other functions. This allows to add extended memory handling to already existing programs without modifying their source (other than adding the include file).

Another solution used in similar memory-debugging tools makes use of dynamic libraries to call the library allocators instead of the standard ones. This has the main drawback of failing portability because it relies on the local dynamic library handling features. It is also not safe to do so because such a mechanism acts upon all programs linked to the C library (e.g. all Unix commands), so any bug in xmemory will affect the whole system. On the other hand, it has the advantage of acting without even having to recompile the application. This trick is used by a number of debuggers and profilers on Linux, but does not satisfy the requirements stated for this module.


next up previous
Next: Virtual memory files Up: Analysis Previous: Analysis
Nicolas Devillard 2002-05-03