C
Summary - Memory management
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.
Exercise 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);.
Show example solution
#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;
}
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.
Test yourself
-
Match the stack parts
- push
- Add element
- pop
- Remove element
- realloc
- Grow array
- free
- Release memory
-
Which memory function does push use in the dynamic stack?
Show answer
realloc — push uses realloc to grow the array by one element.
Next lesson: Module design