Skip to content

Detect memory (de)allocation with new/delete/malloc/free

License

Notifications You must be signed in to change notification settings

Sidelobe/MemorySentinel

Repository files navigation

 ╔╦╗┌─┐┌┬┐┌─┐┬─┐┬ ┬  ╔═╗┌─┐┌┐┌┌┬┐┬┌┐┌┌─┐┬
 ║║║├┤ ││││ │├┬┘└┬┘  ╚═╗├┤ │││ │ ││││├┤ │
 ╩ ╩└─┘┴ ┴└─┘┴└─ ┴   ╚═╝└─┘┘└┘ ┴ ┴┘└┘└─┘┴─┘                            

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)

MemorySentinel is very useful in Unit Tests to:

  • Monitor dynamic memory allocation during certain function calls / operations
  • Simulate out-of-memory conditions (e.g. branch coverage metrics)

Allocation Quota

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.

Usage

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();

Scoped usage

{
  ScopedMemorySentinel sentinel;	
  float* heapObject = new float[32];  
} 
// will assert upon exiting scope

Requirements / Compatibility

  • C++14
  • STL
  • tested with GCC, Clang and MSVC
  • tested with Catch2 Test Framework
  • tested on macos, windows & linux

Status

Sidelobe Build Matrix Linux Sidelobe Build Matrix macos Sidelobe Build Matrix Windows

MemorySentinel Quality Gate Status Coverage Bugs Vulnerabilities Lines of Code Maintainability Rating Reliability Rating Security Rating Technical Debt

About

Detect memory (de)allocation with new/delete/malloc/free

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages