Fixed-size stack
Push and pop on an array-backed stack with overflow and underflow checks. An easy embedded C problem (Buffers and data structures), run and graded in the…
easy · Buffers and data structures · stack · lifo
Implement a last-in, first-out stack. A zero-initialised istack_t is empty.
stack_pushaddsvand returnstrue, or returnsfalsewhen the stack is full.stack_popremoves the most recently pushed value into*vand returnstrue, or returnsfalseand leaves*valone when the stack is empty.
Starter code
bool stack_push(istack_t *s, int32_t v) {
return false;
}
bool stack_pop(istack_t *s, int32_t *v) {
return false;
}Example tests
Last in, first out
istack_t s = { 0 };
stack_push(&s, 1); stack_push(&s, 2); stack_push(&s, 3);
int32_t a = 0, b = 0;
stack_pop(&s, &a); stack_pop(&s, &b);
printf("%d %d\n", a, b);Expected output:
3 2Popping an empty stack
istack_t s = { 0 };
int32_t v = 77;
printf("%d %d\n", stack_pop(&s, &v), v);Expected output:
0 77Learn it first
- Buffers and data structures · Ring buffers, pools, lists and bitmaps on static memory.
More Buffers and data structures problems
- Ring buffer · Implement put and get for a fixed-size FIFO.
- Fill level from two indices · Compute how many items a FIFO holds from its head and tail.
- Overwriting log buffer · Keep only the most recent entries, replacing the oldest when full.
- Sorted insert into a linked list · Insert a caller-provided node into an ascending singly linked list.
- Reverse a linked list · Reverse a singly linked list in place.
- Fixed-block memory pool · Allocate and free fixed-size blocks from a static pool.
- Small priority queue · Keep pending jobs ordered by priority in a fixed array.
- Bitmap operations · Set, clear and test individual bits in a byte array.
- First free slot · Find the first zero bit in a bitmap of a given length.
- Sample history by age · Store the last few samples and read them back by how old they are.
- Bump allocator · Hand out aligned chunks from a static buffer.
- Fix: the console drops characters · A serial console echoes the wrong characters once its receive buffer wraps.
- An opaque FIFO module: fifo.h and fifo.c · Implement a byte FIFO whose layout only fifo.c knows: callers hold a pointer and use four functions.
- Bluetooth speaker: never overwrite unplayed audio · A sample ring buffer that refuses new samples when full instead of overwriting the ones not yet played.