A stack is a linear type of data structure that follows the LIFO (Last-In-First-Out) principle and allows insertion and deletion operations from one end of the stack data structure, that is top.
Stack
Security
#define N 4
int stack[N];
int top = -1;
// Fill Stack
top++; // 0
stack[top] = 1;
top++; // 1
stack[top] = 2;
top++; // 2
stack[top] = 3;
top++; // 3
stack[top] = 4;
struct Node {
int Data;
struct Node *Next;
} *top;
int size = 0;
The pop operation will remove the element in top
of the stack
When we using an array we just decrement top
.
void pop() {
if (top <= 0) {
printf("Stack Underflow\n");
return;
}
stack[top] = 0; // Optional
top--;
}
When using a list we have to free the node
of heap memory.
void pop() {
if (size <= 0) {
printf("Stack Underflow\n");
return;
}
struct Node *tmp = top;
/* Top is always the head of the list.
* When we adding elements we insert them in the begging.
* Same when we remove them. */
top = top->Next;
free(tmp);
size--;
}
The push operation will add an element top the top
of the stack
When using an array we just increment top
.
void push(int value) {
if (top > N) {
printf("Stack Overflow\n");
return;
}
stack[top] = N;
top++;
}
When using a list we have to allocate a node
in heap memory.
void push(int value) {
/* This will create a new node which will point to the current top node.
* This is like inserting in the beggining of a list. */
top = new_node(value, top);
size++;
}
A stack overflow is a type of buffer overflow error that occurs when a computer program tries to use more memory space in the call stack than has been allocated to that stack.
Graphical Representation
/* This Recursive Function Will Be Allocated In The Call Stack.
* We Will Call The Function Over And Over Unitil The Call Stack Is Full.
* Finally The Program Will Crash (Segmentation Fault) */
void infinite_recursion(int n) {
infinite_recursion(n + 1);
}
int main() {
// Get Call Until The Program Crash
infinite_recursion(0);
return 0;
}