╔╦╗┌─┐┌┬┐┌─┐┬─┐┬ ┬ ╔═╗┌─┐┌┐┌┌┬┐┬┌┐┌┌─┐┬
║║║├┤ ││││ │├┬┘└┬┘ ╚═╗├┤ │││ │ ││││├┤ │
╩ ╩└─┘┴ ┴└─┘┴└─ ┴ ╚═╝└─┘┘└┘ ┴ ┴┘└┘└─┘┴─┘
A utility to detect memory allocation and de-allocation in a given scope. Meant to be used for testing environments, not production deployments.
The MemorySentinel hijacks the all the system's variants of new & delete as well malloc & free. When unarmed, it quietly monitors the memory allocation landscape without intervening (quiet infiltration). When armed, and as soon as a "transgression" is detected, the MemorySentinel will become active, and either:
- Throw a
std::bad_alloc(only for allocation funtions) - Log to console (while still allocating normally)
- Register the event silently (status can be queried)
- Monitor dynamic memory allocation during certain function calls / operations
- Simulate out-of-memory conditions (e.g. branch coverage metrics)
The sentinel's strict zero-allocation-tolerance can be softened by calling setAllocationQuota(int numBytes). If this scenario the sentinel will log allocation until the quota is reached and then behave as usual.
MemorySentinel& sentinel = MemorySentinel::getInstance();
sentinel.setTransgressionBehaviour(MemorySentinel::TransgressionBehaviour::THROW_EXCEPTION);
sentinel.setArmed(true);
float* heapObject = new float[32]; // will throw an exception
// After use, disarm Sentinel
sentinel.setArmed(false);
sentinel.clearTransgressions();{
ScopedMemorySentinel sentinel;
float* heapObject = new float[32];
}
// will assert upon exiting scope- C++14, STL
- Catch2 Test Framework
- Supports GCC, Clang; macos & linux -- detects the following (de)allocators:
malloc,calloc,realloc,free,memalign(GLIBC),alloc_aligned,posix_memalign(where available)new,new[],delete,delete[]
- Supports MSVC on Windows (functionality reduced):
new,new[],delete,delete[]