|
NetBurner 3.5.6
PDF Version |
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 amount of "untouched" memory (never allocated)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() still reports 700KB (watermark)mallinfo() reports 900KB (including freed memory)The spaceleft() function acts as a "watermark" showing the largest contiguous block available, while mallinfo() shows total available memory including fragmented blocks.
spaceleft() value cannot increase until the last allocated block is freedShowHeapSpace() - Displays current heap statisticsUserMain() - Main application loop with allocation/deallocation cycleThis example is particularly valuable for understanding: