NetBurner 3.5.8
PDF Version
malloc

Example Path: examples/malloc

Malloc Example Application

Overview

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.

Purpose

The primary goals of this example are to:

  • Demonstrate proper usage of malloc() and free() functions
  • Show how to track heap space usage using spaceleft() and mallinfo()
  • Illustrate memory fragmentation effects when freeing memory in different orders
  • Provide insights into heap memory management for embedded applications

Key Features

Memory Tracking Functions

The application uses two important functions to monitor heap status:

  1. **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.
  2. **mallinfo()** - Returns detailed heap information including both untouched and freed memory

mallinfo Structure

The mallinfo() function returns a structure containing:

  • arena - Total space allocated from system
  • ordblks - Number of non-inuse chunks
  • smblks - Unused (always zero)
  • hblks - Number of mmapped regions
  • hblkhd - Total space in mmapped regions
  • usmblks - Unused (always zero)
  • fsmblks - Unused (always zero)
  • uordblks - Total allocated space
  • fordblks - Total non-inuse space
  • keepcost - Top-most, releasable space

Application Flow

The application runs in a continuous loop performing the following sequence:

Allocation Phase

  1. Allocates 1,000,000 bytes (pA)
  2. Allocates 3,000,000 bytes (pB)
  3. Allocates 512,000 bytes (pC)

Deallocation Phase

The memory is freed in a different order than allocated:

  1. Frees pB (3,000,000 bytes)
  2. Frees pA (1,000,000 bytes)
  3. Frees pC (512,000 bytes)

After each allocation and deallocation, the heap status is displayed showing:

  • Used memory
  • Space left (untouched memory)
  • Total free memory

Memory Fragmentation Example

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:

Example Scenario (matching this application):

  1. Allocate pA (1,000,000 bytes), pB (3,000,000 bytes), then pC (512,000 bytes). Each allocation pulls from the untouched top of the heap, so spaceleft() steps down by roughly each block's size.
  2. Free pB, then pA, then pC. Across all three frees, spaceleft() does not move – not even after the top-most block (pC) is freed.
  3. The freed memory instead shows up in 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.

Key Observations

  • Order Matters: The order of memory deallocation affects heap fragmentation
  • Watermark Effect: spaceleft() never increases on free() – it only shrinks as never-touched memory is handed out. Freed memory is reported by mallinfo(), not spaceleft()
  • Monitoring is Critical: Using both functions provides complete heap visibility
  • Production Considerations: System diagnostics should be disabled in production code

Code Structure

  • ShowHeapSpace() - Displays current heap statistics
  • UserMain() - Main application loop with allocation/deallocation cycle
  • Error handling for failed malloc operations
  • 10-second delay between cycles for observation

Usage Notes

  • The application includes system diagnostics that should be removed for production
  • Memory allocation failures are handled gracefully with error messages
  • The continuous loop allows observation of memory behavior over time
  • All allocated memory is properly freed to prevent memory leaks

Educational Value

This example is particularly valuable for understanding:

  • Dynamic memory management in embedded systems
  • Memory fragmentation effects
  • Proper error handling for memory allocation
  • Heap monitoring techniques
  • The difference between total reusable memory (mallinfo()) and pristine never-allocated memory (spaceleft())

Platform Requirements

  • RTOS environment (uses OSTimeDly)
  • Hardware abstraction layer (HAL)
  • Standard C library with malloc/free support
  • Support for mallinfo() function
  • A board with a multi-megabyte heap. The allocations total ~4.5 MB (1 MB + 3 MB + 512 KB); on a smaller-heap platform the 3 MB allocation will fail and the fragmentation demonstration will not run as described. Scale the sizes down to fit your target if needed.