Drake
Drake C++ Documentation
LimitMalloc Class Referencefinal

Detailed Description

Instantiate this class in a unit test scope where malloc (and realloc, etc.) should be disallowed or curtailed.

Note
This class is currently a no-op in some build configurations:
  • macOS
  • leak sanitizer
  • valgrind tools

Example:

GTEST_TEST(LimitMallocTest, BasicTest) {
std::vector<double> foo(100); // Heap allocation is OK.
{
LimitMalloc guard;
// The guarded code goes here. Heap allocations result in aborts.
std::array<double, 100> stack;
}
std::vector<double> bar(100); // Heap allocation is OK again.
}

Currently, when the device under test violates its allocation limits, the test terminates with an abort(). To better isolate what went wrong, re-run the test in a debugger.

This class is only intended for use in test code. To temporarily use it in non-test code, hack the BUILD.bazel file to mark this library testonly = 0 instead of testonly = 1.

#include <drake/common/test_utilities/limit_malloc.h>

Public Member Functions

 LimitMalloc ()
 Applies malloc limits until this object's destructor is run. More...
 
 LimitMalloc (LimitMallocParams args)
 Applies malloc limits until this object's destructor is run. More...
 
 ~LimitMalloc ()
 Undoes this object's malloc limits. More...
 
int num_allocations () const
 Returns the number of allocations observed so far. More...
 
const LimitMallocParamsparams () const
 Returns the parameters structure used to construct this object. More...
 
Does not allow copy, move, or assignment
 LimitMalloc (const LimitMalloc &)=delete
 
void operator= (const LimitMalloc &)=delete
 
 LimitMalloc (LimitMalloc &&)=delete
 
void operator= (LimitMalloc &&)=delete
 

Constructor & Destructor Documentation

◆ LimitMalloc() [1/4]

Applies malloc limits until this object's destructor is run.

All allocations will fail. For now, only one instance of this class may be created at a time. (In the future, we may allow updating the limits by nesting these guards.)

◆ LimitMalloc() [2/4]

LimitMalloc ( LimitMallocParams  args)
explicit

Applies malloc limits until this object's destructor is run.

A allocations will succeed except for any limits designated in args. For now, only one instance of this class may be created at a time. (In the future, we may allow updating the limits by nesting these guards.)

◆ ~LimitMalloc()

Undoes this object's malloc limits.

◆ LimitMalloc() [3/4]

LimitMalloc ( const LimitMalloc )
delete

◆ LimitMalloc() [4/4]

LimitMalloc ( LimitMalloc &&  )
delete

Member Function Documentation

◆ num_allocations()

int num_allocations ( ) const

Returns the number of allocations observed so far.

◆ operator=() [1/2]

void operator= ( const LimitMalloc )
delete

◆ operator=() [2/2]

void operator= ( LimitMalloc &&  )
delete

◆ params()

const LimitMallocParams& params ( ) const

Returns the parameters structure used to construct this object.


The documentation for this class was generated from the following file: