CodeBlanks Logo Icon CodeBlanks

Summary - Memory management

  • C course
  • Intermediate
  • Lesson 12/116
  • 5 min

Combine malloc, realloc and free to write a dynamic stack.

Designing a dynamic stack

In this summary you'll combine malloc, realloc and free to write a dynamic stack. A stack is a last-in first-out (LIFO) data structure.

The stack holds an int * array and a size counter in the background. push grows the array by one element with realloc and appends the new value. pop returns the last element and decrements size. Shrinking with realloc is not required; just decrementing the size is enough. When done, free the memory with free.

Practice Write a dynamic stack

Declare global int *stack = NULL; and int size = 0;. Write void push(int v); grow with int *tmp = realloc(stack, (size + 1) * sizeof(int));, if tmp do stack = tmp; stack[size] = v; size++;. Write int pop(void); if (size == 0) return -1;, then size--; return stack[size];. In main call push(10); push(20); push(30);, print two pops with printf("%d\n", pop()), then print the remainder with printf("%d\n", stack[0]). Free with free(stack);.

Starter code

main.c
#include <stdio.h>
#include <stdlib.h>

// Declare global stack and size
// Write push and pop functions
// Call push/pop in main and free

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>
#include <stdlib.h>

int *stack = NULL;
int size = 0;

void push(int v) {
    int *tmp = realloc(stack, (size + 1) * sizeof(int));
    if (tmp) {
        stack = tmp;
        stack[size] = v;
        size++;
    }
}

int pop(void) {
    if (size == 0) return -1;
    size--;
    return stack[size];
}

int main(void) {
    push(10);
    push(20);
    push(30);
    printf("%d\n", pop());
    printf("%d\n", pop());
    printf("%d\n", stack[0]);
    free(stack);
    return 0;
}

Expected output

30
20
10

Summary

In this group you learned dynamic memory management. malloc allocates uninitialized, calloc zero-initialized memory; realloc resizes; free releases. Leaks and dangling pointers are the most common bugs.

You combined these to write a dynamic stack with push/pop. Growing with realloc and releasing with free together give a safe and flexible data structure. The advanced string handling and library projects in the next groups build on these foundations.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the stack parts

Term Meaning
push Add element
pop Remove element
realloc Grow array
free Release memory

2 Which memory function does push use in the dynamic stack?

  • free
  • printf
  • realloc Correct answer
  • sizeof

Explanation: push uses realloc to grow the array by one element.

All lessons in Intermediate