Classic C Language Interview Questions for Embedded Systems – Memory Management

1. What are the methods of memory allocation in C language?

▍Technical Principles Explained

In embedded systems, the memory allocation mechanism directly affects the stability and performance of programs. C language manages memory through the following three methods:

Classic C Language Interview Questions for Embedded Systems - Memory Management

Memory Allocation Methods

Low-Level Mechanism Analysis:

1. Static Storage Area

  • Lifecycle: Allocated at program startup, released at process termination
  • Implementation Principle: Allocated by the compiler in the .data segment (initialized) or .bss segment (uninitialized)
  •    int global_var;             // .bss segment   static int static_var = 10; // .data segment

2. Stack Allocation

x86 architecture default stack growth direction: high address → low addressARM Cortex-M uses a full descending stack (SP decreases before storing during PUSH)Classic C Language Interview Questions for Embedded Systems - Memory Management

Stack Memory Allocation

3. Heap Allocation

  • Managed using algorithms like malloc
  • Allocation speed is slow (requires traversing free list)
  • Prone to external fragmentation

Memory Management Structure:

   struct heap_chunk    {       size_t prev_size;  // Size of previous block       size_t size;       // Size of current block (including flags)       struct heap_chunk* fd; // Pointer to free block list       struct heap_chunk* bk;   };

Allocation Algorithm:

Classic C Language Interview Questions for Embedded Systems - Memory Management

Heap Allocation Algorithm

2. What are the differences between heap and stack?

▍Difference Analysis

Classic C Language Interview Questions for Embedded Systems - Memory Management

Heap vs Stack Comparison

Key Differences Explained:

Characteristic Stack Heap
Allocation Speed Single cycle completion (SP register operation) Requires traversing free list (100+ cycles)
Fragmentation Issue None External fragmentation rate can exceed 30%
Hardware Support Dedicated SP register No hardware acceleration
Error Type Stack Overflow Heap Fragmentation
Debugging Difficulty Easy (LR register tracking) Difficult (requires memory analysis tools)

Embedded Development Trap Example:

// Danger: Large array allocation leads to stack overflowvoid unsafe_func() {    uint8_t buffer[2048];  // Crashes in 1KB stack environment    memset(buffer, 0, sizeof(buffer));}// Correct: Use heap allocationvoid safe_func() {    uint8_t *buffer = malloc(2048);    if(buffer)     {        memset(buffer, 0, 2048);        free(buffer);    }}

3. What is the role of the stack in C language?

▍Stack Frame Structure and Function Calls

Classic C Language Interview Questions for Embedded Systems - Memory Management

Stack Frame Structure and Function Calls

ARM Cortex-M Stack Operation Process:

1. When calling a function:

    • Store parameters in R0-R3 registers (excess pushed onto stack)
    • Return address automatically stored in LR register
MOVR0,#0x01; Parameter 1
MOVR1,#0x02; Parameter 2
BLtarget_func; Jump and save LR

2. During function execution:

  • Push to stack to save R4-R11 and other registers that need to be preserved
  • Adjust stack pointer to allocate space for local variables
PUSH{R4-R7,LR}; Save registers
SUBSP,SP,#0x20; Allocate space for local variables

3. When returning from the function:

  • Restore saved registers
  • Return via POP {PC}
ADDSP,SP,#0x20; Release local variables
POP{R4-R7,PC}; Restore registers and return

Interrupt Context Saving Mechanism:

// Cortex-M automatic stack push order
typedef struct {    uint32_t r0, r1, r2, r3, r12, lr, pc, xpsr;} HardwareStackFrame;// Interrupt handling example__attribute__((naked)) void HardFault_Handler(void) {    __asm__ volatile(        "TST LR, #4\n"        "ITE EQ\n"        "MRSEQ R0, MSP\n"        "MRSNE R0, PSP\n"        "B HardFault_Handler_C\n"    );}

4. What is the order of pushing function parameters onto the stack?

Classic C Language Interview Questions for Embedded Systems - Memory Management

Order of Pushing Function Parameters onto the Stack

▍Technical Principles Explained

  • The first four integer parameters are passed via R0-R3 registers
  • The fifth parameter and beyond are passed using the stack (SP+0 offset)
  • Floating-point parameters use S0-S15 registers

Stack Frame Verification Code:

void test_stack(int a, int b, int c) {    printf("&a=%p &b=%p &c=%p\n", &a, &b, &c);     // Output shows: &c < &b < &a (addresses decrease)}int main() {    test_stack(1, 2, 3);  // Trigger stack push operation}

5. What are the hardware-level manifestations of memory leaks?

Classic C Language Interview Questions for Embedded Systems - Memory Management

Hardware-Level Manifestations of Memory Leaks

▍Technical Principles Explained

  • Abnormal reduction in free list nodes of the heap manager
  • Frequent expansion of heap space via _sbrk() system call
  • Continuous decrease in memory fragmentation counter (mallinfo().fordblks)

Embedded Detection Code:

void mem_leak_check() {    struct mallinfo mi = mallinfo();    static int last_free = 0;
    if(mi.fordblks < last_free)     {        log_error("Memory leak! Decreased by %d bytes", last_free - mi.fordblks);    }    last_free = mi.fordblks;}

6. What is a systematic solution for memory leak detection?

▍Implementation Plan

Classic C Language Interview Questions for Embedded Systems - Memory Management

Systematic Solution for Memory Leak Detection

Custom Memory Debugger:

#define MEM_DEBUG#ifdef MEM_DEBUGtypedef struct {    void* ptr;    size_t size;    const char* file;    int line;} MemRecord;static MemRecord mem_table[1024];static size_t mem_usage = 0;void* debug_malloc(size_t s, const char* file, int line) {    void* p = _malloc(s);    if(p)     {        mem_table[mem_usage++] = (MemRecord){p, s, file, line};    }    return p;}void dump_leaks() {    for(int i=0; i<mem_usage; i++)     {        printf("Leak block: %p size=%d @%s:%d\n",               mem_table[i].ptr,               mem_table[i].size,              mem_table[i].file,              mem_table[i].line);    }}#endif

Leave a Comment