- How to model a stack with a
structcontainingtop,capacity, and anint *array - How to allocate both the stack struct and the internal array with
malloc() - How to implement push (add to top) and pop (remove from top) in O(1)
- How to detect overflow and underflow
- How to free the stack in the correct order — inner array first, struct second
Purpose & Objective
To develop a C program that performs push and pop operations and dynamically allocates memory for a stack data structure, we will cover each aspect step by step.
This program in C language shows how to assign dynamically allocated memory to a stack at runtime. It explains the practical use in programming and provides a detailed description of the code including how the output appears.
By demonstrating how to perform actions such as push and pop, this program teaches you how to manage data in a Last In First Out (LIFO) form. It also highlights the importance of dynamic memory allocation for efficient memory usage during execution.
Purpose of this program:
- Understanding stacks: Using a stack data structure with dynamic memory allocation helps build a strong foundation of stacks in computer science.
- Dynamic memory allocation: Learn how to allocate memory dynamically to data structures to meet variable storage needs at runtime.
- Real-life applications: Demonstrates how stacks are used in practical contexts — function call management, expression evaluation, and undo mechanisms.
💡 Quick Definition: A stack is a LIFO data structure — the last element pushed is the first one popped. A dynamic stack allocates its internal array at runtime with malloc(), so its size can be chosen based on user input.
What is a Stack (LIFO)?
A stack is a linear data structure with two operations:
| Operation | Action | Error Condition |
|---|---|---|
push(x) | Add x to the top of the stack | Stack Overflow (stack is full) |
pop() | Remove and return the top element | Stack Underflow (stack is empty) |
Elements are added and removed from the same end. In memory, the stack is an array plus an index tracking the top.
Designing the Stack
Step 1: Define the Stack Structure
The structure holds an int top (index of the topmost element, -1 when empty), an int capacity (maximum size), and an int *array (dynamically allocated block for the elements).
Step 2: Define the Operations
- createStack(capacity) — allocates the struct and the internal array; initializes
top = -1. - push(stack, item) — adds a value to the top.
- pop(stack) — removes and returns the top value.
- isFull / isEmpty — helpers for checking overflow and underflow.
- displayStack — prints the current stack from bottom to top.
Step 3: Dynamic Memory Allocation
The stack array is allocated at runtime based on the user's input for capacity. This makes the stack size flexible and chosen per run.
Step 4: User Interaction
A menu-driven interface lets the user choose push, pop, display, or exit — and see the result immediately.
Step 5: Cleaning Up
Before exiting, the program frees the dynamically allocated memory to prevent memory leaks. Order matters: free the internal array first, then the struct itself.
Real-Life Applications
Stacks are common in a variety of real-life applications:
Managing Function Calls
The compiler and runtime use a stack to manage function calls, return addresses, and local variables.
Expression Evaluation
Stacks help evaluate mathematical expressions by converting them to postfix or prefix notation.
Undo Mechanism
Many applications use stacks to implement undo — storing and repeating previous states or actions.
Complete C Program
Program: Dynamically allocate a stack and perform push and pop operations
#include <stdio.h>
#include <stdlib.h>
/* Structure to represent a stack */
struct Stack {
int top; /* Index of the top element */
int capacity; /* Maximum capacity of the stack */
int *array; /* Array to store stack elements */
};
/* Function to create a stack of given capacity */
struct Stack *createStack(int capacity) {
struct Stack *stack = (struct Stack *)malloc(sizeof(struct Stack));
if (!stack) {
printf("Memory allocation error.\n");
return NULL;
}
stack->capacity = capacity;
stack->top = -1; /* Stack is initially empty */
stack->array = (int *)malloc(stack->capacity * sizeof(int));
if (!stack->array) {
printf("Memory allocation error.\n");
free(stack);
return NULL;
}
return stack;
}
/* Function to check if the stack is full */
int isFull(struct Stack *stack) {
return stack->top == stack->capacity - 1;
}
/* Function to check if the stack is empty */
int isEmpty(struct Stack *stack) {
return stack->top == -1;
}
/* Function to add an element to the stack (push operation) */
void push(struct Stack *stack, int item) {
if (isFull(stack)) {
printf("Stack Overflow.\n");
return;
}
stack->array[++stack->top] = item;
printf("%d pushed to stack.\n", item);
}
/* Function to remove an element from the stack (pop operation) */
int pop(struct Stack *stack) {
if (isEmpty(stack)) {
printf("Stack Underflow.\n");
return -1; /* Return a sentinel value for error */
}
return stack->array[stack->top--];
}
/* Function to display the stack contents */
void displayStack(struct Stack *stack) {
int i;
if (isEmpty(stack)) {
printf("Stack is empty.\n");
return;
}
printf("Stack elements:\n");
for (i = 0; i <= stack->top; ++i) {
printf("%d ", stack->array[i]);
}
printf("\n");
}
/* Main function to demonstrate stack operations */
int main() {
int capacity, choice, item;
struct Stack *stack;
printf("Enter the capacity of the stack: ");
scanf("%d", &capacity);
stack = createStack(capacity);
if (!stack) {
printf("Failed to create stack. Exiting.\n");
return -1;
}
while (1) {
printf("\nStack Operations:\n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Display\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter element to push: ");
scanf("%d", &item);
push(stack, item);
break;
case 2:
item = pop(stack);
if (item != -1)
printf("Popped element: %d\n", item);
break;
case 3:
displayStack(stack);
break;
case 4:
printf("Exiting program.\n");
free(stack->array);
free(stack);
exit(0);
default:
printf("Invalid choice. Please try again.\n");
}
}
return 0;
}
Program Output
Enter the capacity of the stack: 5
Stack Operations:
1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 1
Enter element to push: 10
10 pushed to stack.
Stack Operations:
1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 1
Enter element to push: 20
20 pushed to stack.
Stack Operations:
1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 3
Stack elements:
10 20
Stack Operations:
1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 2
Popped element: 20
Stack Operations:
1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 4
Exiting program.
Step-by-Step Explanation
Understanding the output of this stack program helps you see how stack operations work in practice. Here are the key moments during a run.
1. The initial prompt:
Enter the capacity of the stack: 5
Once you enter the capacity, the program creates a stack with that size. The internal array is allocated dynamically to hold 5 integers.
2. Main menu:
Stack Operations:
1. Push
2. Pop
3. Display
4. Exit
Enter your choice:
The menu repeats for each operation until you choose Exit. It runs inside the while (1) loop.
3. Push operation:
Enter element to push: 10
10 pushed to stack.
The program asks for a value, calls push, and confirms the addition. If the stack is already full, it prints Stack Overflow..
4. Pop operation:
Popped element: 20
The top element is returned and removed. If the stack is empty, the program prints Stack Underflow..
5. Display Stack:
Stack elements:
10 20
Shows every current element from bottom to top. If the stack is empty, it prints Stack is empty..
6. Exiting the program:
Exiting program.
Before exit, the program frees stack->array and then stack — preventing memory leaks.
🎯 Key Takeaway: A dynamic stack is just an array plus an integer. Allocate at creation, free at destruction, and always check overflow/underflow. That's the entire discipline of the data structure.
Frequently Asked Questions
1. Why does the pop function return -1 on underflow?
Because -1 is outside the range of valid data we test for in main — it lets the caller know the operation failed. In production code, you might return a status code or use a separate error flag.
2. Can the stack grow after creation?
Not in this version. If you need growth, use realloc() on stack->array when full. That's a common follow-up exercise.
3. Why is top initialized to -1 instead of 0?
Because -1 means "no elements yet". The first push increments top to 0, then stores at index 0 — the first slot. Starting at 0 would skip the first slot.
4. Why does exit use exit(0) instead of return 0?
Because the exit case is inside a while(1) loop nested in main. exit(0) terminates the process cleanly from anywhere, while return 0 would only work if you could reach it — and inside the infinite loop you can't.
💡 Tip: Compile with gcc -fsanitize=address -g to catch leaks and use-after-free bugs instantly.