Consider this embedded C code that uses stack and heap allocation. What will be printed?
#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; }
Remember that stack variables hold local values and heap variables are dynamically allocated.
The stack variable stack_var is set to 10. The heap variable heap_var is allocated memory and assigned 20. The printf prints both values correctly.
In embedded systems, what is a key difference between stack and heap memory?
Think about how memory is allocated and freed in stack vs heap.
The stack is usually a fixed-size memory region used for local variables and function calls, which is fast and managed automatically. The heap is dynamic memory that can grow and shrink but may cause fragmentation and is slower to allocate.
Analyze the code below. Why does it crash on some embedded platforms?
#include <stdio.h> #include <stdlib.h> void func() { int *ptr; *ptr = 5; printf("Value: %d\n", *ptr); } int main() { func(); return 0; }
Check how the pointer is used before assignment.
The pointer 'ptr' is declared but not initialized to point to valid memory. Writing to '*ptr' causes undefined behavior and likely a crash.
Choose the correct syntax to allocate an integer array of size 5 on the heap.
Remember malloc returns a pointer and needs casting in embedded C.
Option A correctly allocates memory for 5 integers on the heap and casts the void pointer to int pointer. Other options have syntax errors or wrong types.
Given the function below, how many bytes of stack memory are used when example() is called on a 32-bit embedded system?
void example() {
int a = 10;
char b = 'x';
double c = 3.14;
}Consider data type sizes and alignment on a 32-bit system.
On a 32-bit system, int is 4 bytes, char is 1 byte but padded to 4 bytes for alignment, double is 8 bytes. Total stack usage is 4 (int) + 4 (char padded) + 8 (double) = 16 bytes.