0
0
Embedded Cprogramming~20 mins

Stack vs heap in embedded context - Practice Questions

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Embedded Memory Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this embedded C code snippet?

Consider this embedded C code that uses stack and heap allocation. What will be printed?

Embedded C
#include <stdio.h>
#include <stdlib.h>

void func() {
    int stack_var = 10;
    int *heap_var = (int *)malloc(sizeof(int));
    *heap_var = 20;
    printf("Stack: %d, Heap: %d\n", stack_var, *heap_var);
    free(heap_var);
}

int main() {
    func();
    return 0;
}
ACompilation error due to malloc
BStack: 10, Heap: 20
CStack: 10, Heap: 0
DStack: 0, Heap: 20
Attempts:
2 left
💡 Hint

Remember that stack variables hold local values and heap variables are dynamically allocated.

🧠 Conceptual
intermediate
1:30remaining
Which statement best describes stack and heap usage in embedded systems?

In embedded systems, what is a key difference between stack and heap memory?

AHeap memory is only used for interrupt handling
BHeap is fixed size and fast; stack is dynamic and slower
CBoth stack and heap are always the same size in embedded systems
DStack is fixed size and fast; heap is dynamic but slower and fragmented
Attempts:
2 left
💡 Hint

Think about how memory is allocated and freed in stack vs heap.

🔧 Debug
advanced
2:30remaining
Why does this embedded C program crash?

Analyze the code below. Why does it crash on some embedded platforms?

Embedded C
#include <stdio.h>
#include <stdlib.h>

void func() {
    int *ptr;
    *ptr = 5;
    printf("Value: %d\n", *ptr);
}

int main() {
    func();
    return 0;
}
APointer 'ptr' is uninitialized and points to random memory causing undefined behavior
BStack overflow due to large local variable
CHeap memory is not freed causing memory leak
DCompilation error due to missing header
Attempts:
2 left
💡 Hint

Check how the pointer is used before assignment.

📝 Syntax
advanced
1:30remaining
Which option correctly declares a heap allocation for an array in embedded C?

Choose the correct syntax to allocate an integer array of size 5 on the heap.

Aint *arr = (int *)malloc(5 * sizeof(int));
Bint arr = malloc(5 * sizeof(int));
Cint *arr = malloc(sizeof(int[5]));
Dint arr[5] = malloc(sizeof(int) * 5);
Attempts:
2 left
💡 Hint

Remember malloc returns a pointer and needs casting in embedded C.

🚀 Application
expert
3:00remaining
How many bytes are used on the stack after this function call in embedded C?

Given the function below, how many bytes of stack memory are used when example() is called on a 32-bit embedded system?

Embedded C
void example() {
    int a = 10;
    char b = 'x';
    double c = 3.14;
}
A12 bytes
B24 bytes
C16 bytes
D8 bytes
Attempts:
2 left
💡 Hint

Consider data type sizes and alignment on a 32-bit system.