Handling Stack Overflow
What you'll learn: How to prevent a stack from exceeding its memory limits by implementing a safety check before adding new data.
The "Full Tray" Problem
Imagine you have a spring-loaded cafeteria tray dispenser. It can hold exactly 10 trays. If you try to force an 11th tray onto the pile, the spring hits the bottom, and the tray falls off or breaks the mechanism.
In C, a stack has a fixed capacity (the size of the array you used to build it). If you try to push a new element when the stack is already full, you trigger a Stack Overflow. Without a safety check, your program might overwrite other important data in memory, leading to a crash or unpredictable bugs.
Detecting the Limit
To handle an overflow, you must check the status of your stack pointer (usually an index variable like top) before you perform the actual assignment. If top has reached the maximum index of your array, you must refuse the new data and alert the user.
Here is how you implement this guardrail in code:
#include <stdio.h>
#include <stdbool.h>
#define MAX 5 // The stack can only hold 5 integers
int stack[MAX];
int top = -1;
bool push(int value) {
// 1. The Overflow Check
if (top >= MAX - 1) {
printf("Error: Stack Overflow! Cannot add %d.\n", value);
return false; // Indicate failure
}
// 2. Safe to proceed
top++;
stack[top] = value;
printf("Pushed %d onto the stack.\n", value);
return true;
}
int main() {
// Attempting to push 6 items into a 5-slot stack
for (int i = 1; i <= 6; i++) {
push(i);
}
return 0;
}
Why it matters
In low-level programming, C doesn't automatically stop you from writing data past the end of an array. It trusts you to manage the boundaries. By adding an if (top >= MAX - 1) check, you create a "boundary guard" that ensures your stack stays within its allocated "home" in memory. This simple conditional is the difference between a robust application and one that crashes unexpectedly under heavy load.
Key takeaway
Always check if your stack pointer has reached the maximum capacity before performing a push operation to prevent memory corruption.