Bird
Raised Fist0
Embedded Cprogramming~10 mins

Stack overflow detection in Embedded C - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Stack overflow detection
Start Program
↓
Function Call
↓
Push Stack Frame
↓
Check Stack Pointer
↓
Continue
↓
Return
↓
End
When a function is called, a new stack frame is pushed. The system checks if the stack pointer exceeds the limit. If yes, overflow is detected and handled.
Execution Sample
Embedded C
void func() {
  char buffer[10];
  // simulate overflow
  for(int i=0; i<20; i++) {
    buffer[i] = i;
  }
}
This code simulates a stack overflow by writing beyond the buffer size.
Execution Table
StepActionStack Pointer (SP)ConditionResultOutput/Effect
1Enter func(), push stack frameSP=1000SP < STACK_LIMIT(1024)?TrueContinue execution
2Write buffer[0] = 0SP=1000SP < STACK_LIMITTrueNo overflow
3Write buffer[9] = 9SP=1000SP < STACK_LIMITTrueNo overflow
4Write buffer[10] = 10 (overflow)SP=1000SP < STACK_LIMITFalseStack overflow detected!
5Trigger overflow handlerSP=1000--Handle error, stop or reset
6Exit func() due to errorSP=1000--Program halted or recovered
💡 At step 4, writing beyond buffer size causes stack pointer to exceed limit, triggering overflow detection.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
SP10001000100010001000
buffer index-0910-
Overflow FlagFalseFalseFalseTrueTrue
Key Moments - 3 Insights
Why does the stack pointer (SP) not change even when writing beyond buffer?
In this example, SP is fixed for simplicity; actual overflow is detected by comparing write index to buffer size, as shown in execution_table step 4.
What happens when overflow is detected at step 4?
The program triggers an overflow handler to prevent corruption or crash, as shown in step 5 and 6.
Why do we check SP against STACK_LIMIT before continuing?
To ensure the stack does not grow beyond its allocated memory, preventing data corruption or crashes.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, at which step is the stack overflow detected?
AStep 5
BStep 2
CStep 4
DStep 3
💡 Hint
Check the 'Result' column for 'Stack overflow detected!' in the execution_table.
According to variable_tracker, what is the value of Overflow Flag after step 3?
AFalse
BUndefined
CTrue
D1
💡 Hint
Look at the Overflow Flag row under 'After Step 3' in variable_tracker.
If the STACK_LIMIT was increased, how would the execution_table change?
AOverflow detected earlier
BOverflow detected later or not at all
CNo change in overflow detection
DProgram crashes immediately
💡 Hint
Consider the 'Condition' and 'Result' columns in execution_table and how STACK_LIMIT affects them.
Concept Snapshot
Stack overflow detection:
- Stack frames push on function calls
- Stack pointer (SP) tracks usage
- Check SP against STACK_LIMIT
- If SP exceeds limit, trigger overflow handler
- Prevents memory corruption and crashes
Full Transcript
Stack overflow detection happens when a program uses more stack memory than allowed. Each function call pushes a frame on the stack, increasing the stack pointer (SP). Before continuing, the program checks if SP is below a set limit. If SP exceeds this limit, an overflow is detected. The program then triggers an overflow handler to stop or recover safely. In the example, writing beyond a buffer simulates overflow, detected at step 4. The overflow flag changes from false to true, and the handler runs to prevent damage.

Practice

(1/5)
1.

What is the main purpose of stack overflow detection in embedded C?

easy
A. To increase the stack size dynamically
B. To prevent writing data beyond the stack's fixed size
C. To optimize CPU speed
D. To clear the stack memory automatically

Solution

  1. Step 1: Understand stack overflow concept

    Stack overflow occurs when data is pushed beyond the stack's allocated size.
  2. Step 2: Identify purpose of detection

    Detection helps prevent writing beyond stack limits, avoiding crashes and corruption.
  3. Final Answer:

    To prevent writing data beyond the stack's fixed size -> Option B
  4. Quick Check:

    Stack overflow detection = prevent overflow [OK]
Hint: Stack overflow detection stops writes beyond stack size [OK]
Common Mistakes:
  • Thinking stack size can grow automatically
  • Confusing overflow detection with CPU optimization
  • Assuming stack clears itself on overflow
2.

Which of the following code snippets correctly checks for stack overflow before pushing a value?

int stack[10];
int sp = 0; // stack pointer
int value = 5;

// Check before push
if (____) {
    stack[sp++] = value;
}
easy
A. sp < 10
B. sp > 10
C. sp == 10
D. sp >= 10

Solution

  1. Step 1: Understand stack pointer and size

    Stack size is 10, valid indices are 0 to 9, so sp must be less than 10 to push.
  2. Step 2: Choose correct condition

    Condition 'sp < 10' ensures we don't write beyond array bounds.
  3. Final Answer:

    sp < 10 -> Option A
  4. Quick Check:

    Push only if sp less than stack size [OK]
Hint: Check sp < stack size before push [OK]
Common Mistakes:
  • Using sp >= 10 allows overflow
  • Using sp == 10 pushes out of bounds
  • Using sp > 10 misses last valid index
3.

What will be the output of the following code snippet?

int stack[3];
int sp = 0;

void push(int val) {
    if (sp < 3) {
        stack[sp++] = val;
        printf("Pushed %d\n", val);
    } else {
        printf("Stack Overflow!\n");
    }
}

int main() {
    push(1);
    push(2);
    push(3);
    push(4);
    return 0;
}
medium
A. Pushed 1 Pushed 2 Pushed 3 Stack Overflow!
B. Pushed 1 Pushed 2 Pushed 3 Pushed 4
C. Stack Overflow! Stack Overflow! Stack Overflow! Stack Overflow!
D. Pushed 1 Pushed 2 Stack Overflow! Stack Overflow!

Solution

  1. Step 1: Trace push calls and stack pointer

    First three pushes succeed because sp < 3; fourth push fails as sp == 3.
  2. Step 2: Check output for each push

    Outputs "Pushed 1", "Pushed 2", "Pushed 3", then "Stack Overflow!" on last push.
  3. Final Answer:

    Pushed 1 Pushed 2 Pushed 3 Stack Overflow! -> Option A
  4. Quick Check:

    Pushes succeed until sp == 3, then overflow [OK]
Hint: Pushes stop when sp reaches stack size [OK]
Common Mistakes:
  • Assuming push always succeeds
  • Ignoring else branch output
  • Confusing sp increment timing
4.

Identify the bug in the following stack push function that causes stack overflow detection to fail:

void push(int val) {
    if (sp <= 3) {
        stack[sp++] = val;
    } else {
        printf("Overflow detected\n");
    }
}
medium
A. sp is not incremented after push
B. Stack size is not checked at all
C. Condition should be sp < 3, not sp <= 3
D. printf statement is inside if block

Solution

  1. Step 1: Analyze condition sp <= 3 with stack size 3

    sp can be 3, but valid indices are 0,1,2; sp=3 causes out-of-bounds write.
  2. Step 2: Correct condition to prevent overflow

    Use sp < 3 to allow only valid indices 0 to 2.
  3. Final Answer:

    Condition should be sp < 3, not sp <= 3 -> Option C
  4. Quick Check:

    Use strict less than to avoid overflow [OK]
Hint: Use sp < stack size, not <=, to avoid overflow [OK]
Common Mistakes:
  • Allowing sp == stack size causes overflow
  • Not incrementing sp after push
  • Misplacing overflow message
5.

You have a stack of size 5 and want to implement a safe push function that returns 0 on success and -1 on overflow. Which code snippet correctly implements this?

int stack[5];
int sp = 0;

int push(int val) {
    // Fill in condition
    if (__________) {
        stack[sp++] = val;
        return 0;
    } else {
        return -1;
    }
}
hard
A. sp > 5
B. sp <= 5
C. sp == 5
D. sp < 5

Solution

  1. Step 1: Understand stack size and valid indices

    Stack size is 5, so valid indices are 0 to 4; sp must be less than 5 to push safely.
  2. Step 2: Choose condition that prevents overflow

    Condition 'sp < 5' ensures no out-of-bounds write and returns 0 on success.
  3. Final Answer:

    sp < 5 -> Option D
  4. Quick Check:

    Push only if sp less than stack size [OK]
Hint: Return error if sp not less than stack size [OK]
Common Mistakes:
  • Using sp <= 5 allows overflow
  • Returning success on overflow
  • Checking sp == 5 instead of less than
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard