Memory Manager Debugging and Error Handling#

Common Debugging Tips#

Heap Full Issues#

  • Problem: SL_STATUS_NO_MORE_RESOURCE or ENOMEM errors

  • Solution:

    • Check heap usage with statistics API

    • Consider using memory pools for guaranteed allocation

    • Optimize allocation patterns to reduce fragmentation

Memory Corruption#

  • Problem: Unexpected crashes or data corruption

  • Solution:

    • Enable debug assertions

    • Use memory pools for critical allocations

    • Implement proper error checking

Fragmentation Issues#

  • Problem: Allocation failures despite available free memory

  • Solution:

    • Use long-term/short-term allocation strategy

    • Monitor heap statistics regularly

    • Consider memory pool usage for critical allocations

Error Code Handling#

Error Code

Description

Recovery Mechanism

SL_STATUS_OK

Success

N/A

SL_STATUS_FAIL

General failure

Check parameters and retry

SL_STATUS_INVALID_PARAMETER

Invalid parameter

Verify input parameters

SL_STATUS_NULL_POINTER

Null pointer parameter

Check for NULL before calling

SL_STATUS_NO_MORE_RESOURCE

Heap is full

Use memory pools or optimize allocation

SL_STATUS_NOT_INITIALIZED

Memory Manager not initialized

Call sl_memory_init() first

Debug Build Error Handling#

#if (defined(DEBUG_EFM) || defined(DEBUG_EFM_USER))
// errno is set for standard-like functions in debug builds
void *ptr = sl_malloc(size);
if (ptr == NULL) {
  // Check errno for specific error:
  // ENOMEM: heap full
  // EINVAL: invalid parameters
  // ENOTRECOVERABLE: unable to create empty block
}
#endif

Memory Usage Monitoring#

void debug_heap_status(void) {
  sl_memory_heap_info_t heap_info;
  if (sl_memory_get_heap_info(&heap_info) == SL_STATUS_OK) {
    printf("Heap Status:\n");
    printf("  Used: %zu/%zu bytes (%.1f%%)\n",
           heap_info.used_size, heap_info.total_size,
           (float)heap_info.used_size * 100 / heap_info.total_size);
    printf("  Free blocks: %zu\n", heap_info.free_block_count);
    printf("  Largest free: %zu bytes\n", heap_info.free_block_largest_size);
  }
}