I’ve made a debug allocator for the C; hopefully this will make it easier for NYU students to learn C and debug their C programs for CSO. The files are:
free, while tracking file and line numbers of allocations.
These two files provide the following features
reallocmacros - These macros are defined in
debug_allocator.h, and simply call
__debug_reallocrespectively, while also passing in the file and line number they were called at.
debug_allocator.ctracks all allocations made during the program’s execution.
0xdadfadedand freed memory is overwritten with
0xaabcdeff, and overwritten with
checkmacro - This macro calls
__debug_check_alloc, and makes sure that the given pointer is a valid reference to the heap. Additionally, it uses the allocation information given to give better error messages.
To use these files, first download them (and/or copy-paste them) into your project.
Usually C projects come with a source folder, often abbreviated
src, so that’s
where they should go. Then any time you need to use
malloc, add the following
line near the beginning of the file:
Then, just use
malloc normally! The macros will take care of the rest.
Please note: don’t keep these files in your project! They’re useful for debugging, but are terrible for performance. Every deallocation is a linear scan through the list of all allocations that you’ve made over the course of the program, so ultimately a program that just allocates and then immediately deallocates a few hundred times is quadratic.
This allocator doesn’t do much, but what it does still might be worth explaining.
__FILE__is a macro that expands to the name of the file it is used in, and
__LINE__likewise expands to the line number of the file it is used in; this means that if
__debug_alloc(x, __FILE__, __LINE__), then
__debug_allocwill get access to the file and line number it was called at, which is exactly what we want.
AllocVecto emulate the behavior of an
ArrayListin Java or a
vectorin C++. Every time you allocate, it does the equivalent of
ArrayList.add, and when you deallocate it searches through the list of allocations and marks the correct allocation as freed.