Stack and Undefined Behavior

In the lecture, an array was used to implement a simple stack that can store a maximum of 5 integer values. You can find the program code (File: stack.abc) at the end of the task.

Tasks

  • Change the instructions in main so that two push operations are executed first, followed by three pop operations. Confirm that the program compiles but encounters a runtime error during execution.

  • Modify the instructions in main so that six push operations are executed first, followed by three pop operations. Again, confirm that the error is detected at runtime.

  • Comment out the assertions in the functions push and pop, and repeat the previous two subtasks. Whether an error occurs or the program seems to execute correctly cannot be predicted. However, it is highly likely that an error will occur if you modify the instructions in main so that a pop operation is followed by a push operation.

  • Remove the comments for the assertions in push and pop.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@ <stdio.hdr>

global
    stack: array[5] of int,
    stackSize: int = 0;

fn push(val: int)
{
    assert(stackSize < sizeof(stack) / sizeof(stack[0]));
    stack[stackSize++] = val;
}

fn pop(): int
{
    assert(stackSize > 0);
    return stack[--stackSize];
}

fn main()
{
    push(3);
    push(4);
    pop();
}