Most beginners assume data structures are static. They aren’t. A linked stack is a dynamic beast. It grows and shrinks on the fly. You don’t pre-allocate memory. You grab it when you need it. Release it when you’re done.
This example uses integers. Change typedef int stack_data to float or char if you want. The logic stays the same.
The Interface
Look at the header. It’s a contract.
stack_init sets up the mess. stack_clear wipes it out. stack_empty tells you if there’s anything left. push shoves data in. pop yanks it out.
Simple. Clean.
The Engine
The code file hides the guts.
top points to the newest item. NULL means empty.
stack_init just resets top to NULL. Done.
stack_clear pops until empty. It’s a loop. It’s cheap.
stack_empty checks if top is NULL. Returns 1 if true. 0 if false.
stack_push does the heavy lifting.
It allocates memory. Sets the data. Links it to the old top. Updates top.
stack_pop reverses the process.
It grabs the data. Moves top down. Frees the old node. Returns the value.
If the stack is empty? It returns garbage. Don’t pop from an empty stack.
Information Hiding
This is key.
You only see the header. You don’t see the code.
The stack could use arrays. Pointers. Files. A linked list. It doesn’t matter.
As long as the interface works, you don’t care how it’s built.
That’s information hiding. It’s not just a buzzword. It’s how you build software that doesn’t break when you change the internals.
C Gotchas
C doesn’t forgive mistakes.
- Parentheses matter.
(*p).iis not the same as*p.i. One dereferences the pointer first. The other accesses the member then dereferences. Get it wrong and you crash. - Memory leaks. Never just set
top = NULL. You orphan every node in the list. You lose the data. You lose the memory. Usefree. Always. - Include headers.
NULLlives instdio.h. If you forget it, your code might compile on some compilers. It won’t on others. Or it’ll defineNULLas zero in a weird way. Includeif you use pointers.
What’s Next?
The basic stack is simple. Real stacks need more.
Add dup. Duplicate the top element. Add count. Return the number of items. Add add. Pop the top two, add them, push the result.
Build a driver program. Write a makefile. Compile it. Run it.
If it crashes, you missed a free. Or you accessed freed memory. Debug it.
The Reality Check
Dynamic allocation is fast. Until it isn’t.
malloc and free have overhead. In tight loops, it adds up.
But for general use? It’s flexible. It’s standard. It’s what you’ll see in most C codebases.
The linked stack is a building block.
You’ll use it for function calls. For expression evaluation. For undo buttons.
It’s everywhere.
Just remember: if you allocate it, you free it. Or else.
“Code is like humor


























