Skip to content

dtledger

Manual allocation accounting with per-class counters and watermarks

This group of functions provides manual allocation tracking for per-class ledgers. It provides simple visibility into instance and byte usage. Mainly this is used in unit tests to ensure memory is not leaked. The implementation is done with low overhead and no dynamic allocation.

At the current time, there are ledgers for:

  • dtbuffer for heap-backed buffer descriptors
  • dtheaper for raw heap allocations
  • dtstr for dynamic strings
  • dterr for error objects with heap-allocated messages

Mini-guide

  • Define the static storage exactly once per tracked class by using DTLEDGER_REGISTER
  • Reference the ledger from other translation units by using DTLEDGER_DECLARE.
  • Increment counters only on successful allocation paths by using DTLEDGER_INCREMENT
  • Decrement counters on free paths by using DTLEDGER_DECREMENT.
  • Access the ledger structure members directly for custom reporting.
  • Format a human-readable summary by calling dtledger_to_string.

Example

#include <inttypes.h>
#include <dtcore/dtledger.h>

DTLEDGER_DECLARE(Foo)

void example(void)
{
    DTLEDGER_REGISTER(Foo);

    DTLEDGER_INCREMENT(Foo, 128);
    DTLEDGER_DECREMENT(Foo, 128);

    char buf[256];
    dtledger_to_string(Foo_ledger, buf, (int32_t)sizeof(buf));
}

Data structures

dtledger_t

This type holds counters and watermarks for a named ledger.

Members:

const char* class_name Name associated with the ledger.
int32_t bytes_balance Current byte balance.
int32_t bytes_high_water_mark Highest observed byte balance.
int32_t bytes_low_water_mark Lowest observed byte balance.
int32_t bytes_total Cumulative bytes added to the ledger.
int32_t count_balance Current instance balance.
int32_t count_high_water_mark Highest observed instance balance.
int32_t count_low_water_mark Lowest observed instance balance.
int32_t count_total Cumulative instances added to the ledger.

Macros

DTLEDGER_DECLARE

DTLEDGER_DECLARE(CLASS_NAME)

Declares an external dtledger_t* for a class-specific ledger.

DTLEDGER_DECREMENT

DTLEDGER_DECREMENT(CLASS_NAME, BYTES)

Decrements the ledger balances and updates low-water marks.

DTLEDGER_INCREMENT

DTLEDGER_INCREMENT(CLASS_NAME, BYTES)

Increments the ledger totals and balances and updates high-water marks.

DTLEDGER_REGISTER

DTLEDGER_REGISTER(CLASS_NAME)

Defines storage for a class-specific ledger and exposes a dtledger_t* pointer to it.

Functions

dtledger_to_string

Formats the current ledger counters into a caller-provided buffer.

Params:

dtledger_t* ledger Ledger to format.

char* buffer Destination buffer to receive the formatted text.

int32_t buffer_size Size of buffer in bytes.

Return: void No return value.