/* An interface to functions that help allocate, free, and track memory references. Author: Byron Weber Becker Inspired by code in "Writing Solid Code" by Steve Maguire */ #ifndef __MEM_H__ #define __MEM_H__ #include #include #define byte unsigned char /* Intent: Allocate a new block of memory. Pre: size > 0 Post: Produces a pointer or NULL if result is not NULL, then result is set to point to size bytes of memory a record is kept that this block of memory was allocated otherwise, no change */ #define dmalloc(size) dmalloc_((size), __FILE__, __LINE__) /* Intent: Free a block of memory previously allocated with dmalloc. Pre: pv points to memory previously allocated with dmalloc Post: Produces void The memory is freed. The record kept when the memory was allocated is deleted. */ void dfree(void *pv); // These two functions are most easily called by using the macros, above. void* dmalloc_(size_t size, char *file, int line); /* These should only be used in "debugging" code Typical use: // code using dmalloc and dfree UnmarkAllBlocks(); for each known memory reference, p { MarkMemoryRef(p); } if (NumUnmarkedBlocks() > 0) { printf("Memory Leaks!\n"); PrintUnmarkedBlocks(); } */ /* Intent: Mark that the memory referenced by pv is known to be still in use. Pre: pv points to memory allocated with dmalloc Post: Produces void the memory referenced by pv is marked as having a known reference */ void MarkMemoryRef(void *pv); /* Intent: Clear all the records of which blocks of memory have known references. Do this before marking known memory references to check for leaks. Pre: true Post: Produces void All records of which blocks of memory have known references are cleared. */ void UnmarkAllBlocks(void); /* Intent: Print a list of all the memory blocks that aren't marked with MarkMemoryRef. These blocks probably should have been freed but were not. Pre: true Post: Produces void. Each unmarked block has its size and the file and line number where it was allocated printed to stderr. */ void PrintUnmarkedBlocks(void); /* Intent: Count the number of blocks that have been allocated but not yet freed. Pre: true Post: Produces blocksAllocated - blocksFreed */ int NumBlocks(void); /* Intent: Count the number of blocks that have not been marked. Pre: true Post: Produces blocksAllocated - blocksFreed - blocksMarked */ int NumUnmarkedBlocks(void); #endif