cmocka  1.1.2
Unit testing library with mock support
Functions
Dynamic Memory Allocation
Collaboration diagram for Dynamic Memory Allocation:

Functions

void * test_malloc (size_t size)
 Test function overriding malloc. More...
 
void * test_calloc (size_t nmemb, size_t size)
 Test function overriding calloc. More...
 
void * test_realloc (void *ptr, size_t size)
 Test function overriding realloc which detects buffer overruns and memoery leaks. More...
 
void test_free (void *ptr)
 Test function overriding free(3). More...
 

Detailed Description

Memory leaks, buffer overflows and underflows can be checked using cmocka.

To test for memory leaks, buffer overflows and underflows a module being tested by cmocka should replace calls to malloc(), calloc() and free() to test_malloc(), test_calloc() and test_free() respectively. Each time a block is deallocated using test_free() it is checked for corruption, if a corrupt block is found a test failure is signalled. All blocks allocated using the test_*() allocation functions are tracked by the cmocka library. When a test completes if any allocated blocks (memory leaks) remain they are reported and a test failure is signalled.

For simplicity cmocka currently executes all tests in one process. Therefore all test cases in a test application share a single address space which means memory corruption from a single test case could potentially cause the test application to exit prematurely.

Function Documentation

◆ test_calloc()

void* test_calloc ( size_t  nmemb,
size_t  size 
)

Test function overriding calloc.

The memory is set to zero.

Parameters
[in]nmembThe number of elements for an array to be allocated.
[in]sizeThe size in bytes of each array element to allocate.
Returns
A pointer to the allocated memory, NULL on error.
See also
calloc(3)

◆ test_free()

void test_free ( void *  ptr)

Test function overriding free(3).

Parameters
[in]ptrThe pointer to the memory space to free.
See also
free(3).

◆ test_malloc()

void* test_malloc ( size_t  size)

Test function overriding malloc.

Parameters
[in]sizeThe bytes which should be allocated.
Returns
A pointer to the allocated memory or NULL on error.
#ifdef UNIT_TESTING
extern void* _test_malloc(const size_t size, const char* file, const int line);
#define malloc(size) _test_malloc(size, __FILE__, __LINE__)
#endif
void leak_memory() {
int * const temporary = (int*)malloc(sizeof(int));
*temporary = 0;
}
See also
malloc(3)

◆ test_realloc()

void* test_realloc ( void *  ptr,
size_t  size 
)

Test function overriding realloc which detects buffer overruns and memoery leaks.

Parameters
[in]ptrThe memory block which should be changed.
[in]sizeThe bytes which should be allocated.
Returns
The newly allocated memory block, NULL on error.