|
NetBurner 3.5.8
PDF Version |
Example Path: examples/malloc
This application demonstrates dynamic memory allocation and deallocation using malloc() and free() functions. It showcases how to monitor heap space usage and illustrates the concept of memory fragmentation in embedded systems.
The primary goals of this example are to:
malloc() and free() functionsspaceleft() and mallinfo()The application uses two important functions to monitor heap status:
spaceleft()** - Returns the size of the "untouched" top-of-heap region that has never been handed to the allocator. This is a high-water mark that only shrinks; free() does not replenish it (freed blocks go onto the free list instead). The SDK diagnostics report this same value as MaxSingleBlock.mallinfo()** - Returns detailed heap information including both untouched and freed memoryThe mallinfo() function returns a structure containing:
arena - Total space allocated from systemordblks - Number of non-inuse chunkssmblks - Unused (always zero)hblks - Number of mmapped regionshblkhd - Total space in mmapped regionsusmblks - Unused (always zero)fsmblks - Unused (always zero)uordblks - Total allocated spacefordblks - Total non-inuse spacekeepcost - Top-most, releasable spaceThe application runs in a continuous loop performing the following sequence:
The memory is freed in a different order than allocated:
After each allocation and deallocation, the heap status is displayed showing:
This application demonstrates an important concept in dynamic memory management. When memory is freed in a different order than it was allocated, it can lead to fragmentation:
spaceleft() steps down by roughly each block's size.spaceleft() does not move – not even after the top-most block (pC) is freed.mallinfo().fordblks (the fragmented free list), which is why the reported "free" total climbs back up while spaceleft() stays put.The key takeaway: spaceleft() is a high-water mark of never-touched memory. It only ever shrinks (as fresh memory is handed out) and is never replenished by free() – reclaimed blocks go onto the free list, not back to the watermark. Use mallinfo() (or the "free" total this app prints) to see memory that has been freed and is available for reuse; use spaceleft() to see how much pristine, never-allocated memory remains.
spaceleft() never increases on free() – it only shrinks as never-touched memory is handed out. Freed memory is reported by mallinfo(), not spaceleft()ShowHeapSpace() - Displays current heap statisticsUserMain() - Main application loop with allocation/deallocation cycleThis example is particularly valuable for understanding:
mallinfo()) and pristine never-allocated memory (spaceleft())