C Program: Dynamic Stack & Push/Pop
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program to Dynamically Allocate Memory for a Stack and Perform Push and Pop Operations

📑 On this page:
  • Purpose & Objective
  • What is a Stack (LIFO)?
  • Designing the Stack
  • Real-Life Applications
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to model a stack with a struct containing top, capacity, and an int *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:

  1. Understanding stacks: Using a stack data structure with dynamic memory allocation helps build a strong foundation of stacks in computer science.
  2. Dynamic memory allocation: Learn how to allocate memory dynamically to data structures to meet variable storage needs at runtime.
  3. 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.

C program to dynamically allocate memory for a stack and perform push and pop operations

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 stackStack Overflow (stack is full)
pop()Remove and return the top elementStack 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.

📖 Related Tutorials

  • malloc in C
  • free in C
  • 4. Dynamic Linked List and Reverse
  • 6. Dynamic Binary Search Tree
  • All DMA Assignments

Previous Topic: -->> 4. Dynamic Linked List & Reverse   ||   Next topic: -->> 6. Dynamic Binary Search Tree


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.