What is the output of this embedded C code snippet that uses a guard variable to detect stack overflow?
#include <stdio.h> #define STACK_SIZE 5 int stack[STACK_SIZE]; int top = -1; int guard = 0xDEADBEEF; void push(int val) { if (top >= STACK_SIZE - 1) { printf("Stack overflow detected!\n"); return; } stack[++top] = val; } int main() { for (int i = 0; i < STACK_SIZE; i++) { push(i); } // Overwrite guard to simulate overflow guard = 0xBADCAFE; if (guard != 0xDEADBEEF) { printf("Stack overflow detected by guard!\n"); } else { printf("No overflow detected.\n"); } return 0; }
Look at how the guard variable is changed and checked after pushing elements.
The code pushes exactly STACK_SIZE elements, so no overflow message from push(). Then the guard variable is manually changed to simulate overflow detection. The check detects this and prints "Stack overflow detected by guard!" only.
Which of the following is the most common cause of stack overflow in embedded C programs?
Think about what uses stack space directly.
Local variables inside functions are stored on the stack. Large arrays declared locally consume a lot of stack space and can cause overflow. Global variables and malloc() use different memory areas. Passing parameters by value uses stack but usually less than large arrays.
What is the cause of stack overflow in this recursive function?
void recurse(int count) { int buffer[1000]; if (count == 0) return; recurse(count - 1); } int main() { recurse(1000); return 0; }
Consider how much stack space each call uses and how many calls happen.
Each recursive call allocates a large local array on the stack. With 1000 calls, the total stack usage exceeds the stack size, causing overflow. The base case is correct and recursion depth is large.
Which option correctly declares a stack guard variable and checks it to detect overflow?
int stack_guard = 0xCAFEBABE; void check_stack() { if (stack_guard != 0xCAFEBABE) { // Overflow detected } }
Check for missing semicolons, correct if syntax, and comparison operators.
Option B is correct syntax. Option B misses semicolon after variable declaration. Option B misses parentheses in if condition. Option B uses assignment '=' instead of comparison '!='.
Given a stack size of 32 KB and each recursive call uses 512 bytes of stack, what is the maximum safe recursion depth to avoid stack overflow?
Divide total stack size by stack used per call.
32 KB = 32768 bytes. Each call uses 512 bytes. 32768 / 512 = 64 calls maximum before overflow.