You can implement the global new
and delete
operators like this:
#include <stdlib.h>
static size_t curUsage = 0, maxUsage = 0;
void* operator new (size_t size) {
curUsage += size;
if(maxUsage < curUsage) maxUsage = curUsage;
size_t* result = (size_t*)malloc(size + sizeof(size_t));
*result = size;
return result + 1;
}
void operator delete (void *pointer) {
size_t* originalPtr = (size_t*)pointer - 1;
curUsage -= *originalPtr;
free(originalPtr);
}
Assuming you are using gcc
, you can then output the max memory usage at the end of the run by simply adding this function:
#include <stdio.h>
__attribute__ ((destructor)) void printMaxUsage() {
printf("max memory usage: %jd bytes\n", maxUsage);
}
This will catch any allocation made with new
and delete
. However, it won't account for used stack space. If you need to take that into account (due to deep recursion and/or large local variables), you must use a different approach. However, for well behaved code, the above should be good enough.
Note that you don't need any changes to any other files, you just have to link in these three functions, and you get the output.