╔╦╗┌─┐┌┬┐┌─┐┬─┐┬ ┬ ╔═╗┌─┐┌┐┌┌┬┐┬┌┐┌┌─┐┬
║║║├┤ ││││ │├┬┘└┬┘ ╚═╗├┤ │││ │ ││││├┤ │
╩ ╩└─┘┴ ┴└─┘┴└─ ┴ ╚═╝└─┘┘└┘ ┴ ┴┘└┘└─┘┴─┘
A utility to detect memory allocation and de-allocation in a given scope. Meant to be used for testing environments.
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
- 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
- tested with GCC, Clang and MSVC
- tested with Catch2 Test Framework
- tested on macos, windows & linux