Chapter 6: Stacks

Chapter 6: Stacks · Study Questions
Stack ADTArray-based stackLinked stackMemory and leaksThe call stackMultiple stacks
Sercan KÜLCÜ · Giresun University · Computer Engineering

Multiple Choice · Stack ADT

Question 1: An Order That Cannot Be Obtained

The letters A, B, C, D, E are pushed onto a stack in this order; pops may be interleaved at any moment. Which of the following pop orders is impossible?

C: When D comes out first, A, B, C are on the stack and C is on top. After E is pushed and popped, C comes out; at that point B is on top, so A cannot come out before it. Option A is possible: push A, B, C → pop C, B → push D, E → pop E, D, A.

Classic Question · Array-Based Stack

Question 2: push/pop That Return bool

The code below is run with a struct stack with CAP = 4. What does the program print?

Stack s; int x, i;
stack_init(&s);
for (i = 1; i <= 5; i++)
  printf("%d", push(&s, i * 10));
printf("\n");
pop(&s, &x); pop(&s, &x);
push(&s, x + 1);
while (pop(&s, &x))
  printf("%d ", x);
Show answer

Output:

11110
31 20 10 
  • 10, 20, 30, 40 are pushed, each push returns 1 (true). At the fifth push 50 is not added because top == CAP - 1, and 0 (false) is returned; the program continues.
  • Two pops remove 40 and 30; the last value is x = 30. Then 31 is pushed. Stack (bottom to top): 10 20 31.
  • The loop empties the stack: 31 20 10. The fourth pop returns false and the loop ends.

Multiple Choice · Array-Based Stack

Question 3: If *top++ Is Written

In the routine push the last line is written as stack[*top++] = item;. What happens when it is called with an empty stack (top = -1)?

B: Postfix ++ binds tighter than unary *: *(top++). The old *top (−1) is used as the index, then only the local pointer advances. Memory before the array is corrupted (undefined behavior) and the caller's counter never changes. The correct form is stack[++*top].

Step-by-Step Trace · Array-Based Stack

Question 4: Binary Conversion with a Stack

How does the stack change in the call print_binary(13), and what is printed?

01234top = -1

Empty stack created; top = -1.

101234top = 0

13 % 2 = 1 onto the stack; the lowest bit is found first.

101234top = 0

n = 13 / 2 = 6 (integer division).

1001234top = 1

6 % 2 = 0 onto the stack; n = 3.

10011234top = 2

3 % 2 = 1 onto the stack; n = 1.

100112134top = 3

1 % 2 = 1 onto the stack; n = 0 and the loop ends.

10011234top = 2

pop gives the most recently pushed bit: the highest bit is printed first.

1001234top = 1

The next bit is 1.

101234top = 0

The next bit is 0.

01234top = -1

The last bit is 1. The next pop returns false, the loop ends: 13 = 1101₂.

void print_binary(int n) {
  Stack s; int b;
  stack_init(&s);
  while (n > 0) {
    push(&s, n % 2);
    n /= 2;
  }
  while (pop(&s, &b))
    printf("%d", b);
}

Multiple Choice · Array-Based Stack

Question 5: The Opaque Type

stack.h contains only the declaration typedef struct Stack Stack; and the operation prototypes; the fields of struct Stack are defined in stack.c. What happens if the client file contains Stack *s = stack_create(10); s->top = -1;?

B: The client file cannot see inside struct Stack; the compiler cannot know where the top field is and reports an error. This is the point of an opaque type: client code only calls operations such as push and pop, and is unaffected even if the implementation changes.

Classic Question · Array-Based Stack

Question 6: Bugs in stack_create

The version of stack_create below has three bugs (64-bit system; struct Stack { int *data; int top, cap; }). Find and fix them.

Stack *stack_create(int cap) {
  Stack *s = malloc(sizeof s);
  s->data = malloc(cap * sizeof(int));
  if (s->data == NULL) return NULL;
  s->top = -1; s->cap = cap;
  return s;
}
Show answer
  • sizeof s is the size of the pointer (8 bytes); the structure is 16 bytes. Writes go beyond the allocated block. The correct form is sizeof *s.
  • The result of the first malloc is not checked; if it returns NULL, s->data crashes.
  • If data cannot be allocated, the function returns without freeing s: a memory leak.
Stack *stack_create(int cap) {
  Stack *s = malloc(sizeof *s);
  if (s == NULL) return NULL;
  s->data = malloc(cap * sizeof *s->data);
  if (s->data == NULL) {
    free(s); return NULL;
  }
  s->top = -1; s->cap = cap;
  return s;
}

Step-by-Step Trace · Linked Stack

Question 7: malloc and free in a Linked Stack

This code is run with a linked stack. How does memory look after each line; how many malloc and free calls are made in total?

topNULL

Empty stack: top = NULL. No memory has been allocated yet.

top4NULL

push: a new node is allocated, link points to the old top (NULL), top moves to the new node.

top74NULL

7 is inserted at the front: 7 → 4 → NULL.

top4NULL7freed

pop: the value is read, top advances to 4, the node of 7 is released with free.

top94NULL

A new node is allocated: the released memory may be reused, but the address is not guaranteed.

top294NULL

Stack: 2 → 9 → 4 → NULL. Three live nodes = 4 malloc − 1 free.

topNULL

stack_clear releases every node: malloc = free = 4, no leak.

node *top = NULL; int x;
push(&top, 4);
push(&top, 7);
pop(&top, &x); printf("%d ", x);
push(&top, 9);
push(&top, 2);
stack_clear(&top);

Classic Question · Linked Stack

Question 8: Order of Assignments

In the linked push the last two assignments have been swapped. After push(&top, 1) and push(&top, 2) on an empty stack, how does memory look, and what does a pop loop do afterwards?

bool push(node **top, int x) {
  node *new_node = malloc(sizeof *new_node);
  if (new_node == NULL) return false;
  new_node->data = x;
  *top = new_node;
  new_node->link = *top;
  return true;
}
Show answer

Because *top = new_node is done first in every push, new_node->link = *top links the node to itself (at the first push, 1 points to itself); at the second push the old list (the node of 1) is lost.

top21no pointer points to it
  • The node of 1 is a memory leak: no pointer points to it any more.
  • The first pop returns 2, *top = old->link again points to the same node, then the node is released: top becomes a dangling pointer. The second pop reads freed memory (undefined behavior).
  • Correct order: first new_node->link = *top;, then *top = new_node;.

Multiple Choice · Linked Stack

Question 9: Unnecessary malloc

The pop routine of a linked stack is written as below. What happens if a stack of 1000 items is emptied with it?

bool pop(node **top, int *x) {
  node *old = malloc(sizeof *old);
  if (*top == NULL) return false;
  old = *top;
  *x = old->data;
  *top = old->link;
  free(old);
  return true;
}

D: The assignment old = *top; overwrites the only address of the block allocated on the first line; that block can never be freed. Measured with counting malloc/free: 1000 extra mallocs for 1000 pops, 0 matching frees. If it is emptied with a while (pop(...)) loop, the last call made on the empty stack also leaks a block (1001). old is only a pointer; no memory needs to be allocated for it.

Multiple Choice · Linked Stack

Question 10: Memory of the Nodes

On a 64-bit system int is 4 bytes and a pointer is 8 bytes. With nodes struct node { int data; struct node *link; }, how many bytes do the nodes of a linked stack holding 1000 integers take (excluding malloc's own overhead)?

C: The pointer is aligned to an 8-byte boundary; after data, 4 bytes of padding are added and sizeof(node) is 16 (measured). The same data takes 4000 bytes in an array-based stack; the price of a linked stack is a pointer and padding per item.

Classic Question · Linked Stack

Question 11: An Order-Preserving Copy

Write node *stack_copy(const node *top), which returns a copy of a linked stack made of new nodes, preserving the order. The topmost item must be first in the copy as well; if memory runs out, everything allocated so far must be released.

Show answer
node *stack_copy(const node *top) {
  node *head = NULL, **tail = &head;
  for (; top; top = top->link) {
    node *new_node = malloc(sizeof *new_node);
    if (new_node == NULL) {
      stack_clear(&head); return NULL;
    }
    new_node->data = top->data;
    new_node->link = NULL;
    *tail = new_node;
    tail = &new_node->link;
  }
  return head;
}

Copying with push would reverse the order, so nodes are appended at the end. tail is the address of the last link of the copy (a pointer to a pointer): &head for the first node. Time O(n); in a counting test malloc = free.

Multiple Choice · Call Stack

Question 12: Address of a Local Array

Which statement is true about the pointer returned by make()?

int *make(void) {
  int a[3] = {1, 2, 3};
  return a;
}

A: a lives in the call frame of make; on return the frame is popped and that memory may be used by later calls (a dangling pointer). The compiler only warns (GCC -Wreturn-local-addr, Clang -Wreturn-stack-address); it does not stop the build. Fix: allocate from the heap with malloc, or take the array from the caller.

Classic Question · Call Stack

Question 13: Number of Calls and Depth

When f(5) is called, how many f calls are made in total? What is the maximum number of frames on the call stack at the same time (including main)?

void f(int n) {
  if (n <= 1) return;
  f(n - 1);
  f(n - 2);
}
Show answer

The number of calls C(n) = 1 + C(n−1) + C(n−2), C(1) = C(0) = 1: C(2) = 3, C(3) = 5, C(4) = 9, C(5) = 15.

At any moment the stack holds the frames of only one path: f(5) → f(4) → f(3) → f(2) → f(1). With these 5 frames and main, at most 6.

Time is proportional to the total number of calls, stack memory to the deepest path. Verified with a counting program.

Step-by-Step Trace · Multiple Stacks

Question 14: Two Stacks in One Array

Starting from empty, the following are performed in order: push2(1,5), push2(2,9), push2(2,4), push2(1,7), push2(2,3), push2(1,8), push2(2,6) and pop2(2). Which call fails?

012345

M = 6. Stack 1 grows from left to right, stack 2 from right to left. Empty: top1 = −1, top2 = M.

5012345top1

push2(1, 5): top1 + 1 ≠ top2; memory[++top1] = 5.

50123495top1top2

push2(2, 9): memory[--top2] = 9; top2 = 5.

501234495top1top2

push2(2, 4): top2 = 4.

5071234495top1top2

push2(1, 7): top1 = 1.

50712334495top1top2

push2(2, 3): top2 = 3.

507182334495top1top2

push2(1, 8): top1 = 2. Now top1 + 1 == top2: the array is completely full.

507182334495top1top2

push2(2, 6) returns false. The full condition is shared by the two stacks: no cell is wasted.

50718234495top1top2

pop2(2): returns memory[top2++] = 3. The freed cell can now be used by either stack.

bool push2(int k, int x) {
  if (top1 + 1 == top2) return false;
  if (k == 1) memory[++top1] = x;
  else        memory[--top2] = x;
  return true;
}

Multiple Choice · Multiple Stacks

Question 15: Segment Boundaries

A memory of m = 20 cells is divided equally among n = 4 stacks; initially top[i] = boundary[i] = (m/n)·i − 1 and boundary[n] = m − 1. Which cells does stack 2 use, and what are the empty and full conditions?

A: boundary = [−1, 4, 9, 14, 19]. Stack i uses the range memory[boundary[i]+1 .. boundary[i+1]]: 10..14. Empty: top[2] == boundary[2] = 9; full: top[2] == boundary[3] = 14. Option C takes top to be the index of the first item; but in an empty stack top points one before the segment.

Multiple Choice · Summary

Question 16: Pop Orders for Three Items

1, 2, 3 are pushed in this order; pops may be inserted at any moment. How many different output orders can be obtained, and which one cannot?

D: If 3 comes out first, 1 and 2 are on the stack and 2 is on top; 1 cannot come out before it. 2 3 1 is possible: push 1, push 2, pop, push 3, pop, pop. The number of possible orders is a Catalan number: C₃ = 5.

The End

Chapter 6: Stacks: Study Questions
Lecture slides: Chapter 6: Stacks · Lecture notes
1 / 1 Sercan KÜLCÜ. All rights reserved.