Testing and Debugging
Boundary Check
An index check prevents the program from reading outside an array.
range guard
The guard checks both lower and upper bounds before indexing.
fallback value
The fallback path gives a predictable value for out-of-range input.
Boundary Check
boundary_check.c
Replay: real traced execution (multi-file project)
#include <stdio.h>
int main(void) {
int index = 1;
int values[3] = {10, 20, 30};
int selected = -1;
if (index >= 0 && index < 3) {
selected = values[index];
}
printf("selected=%d\n", selected);
return 0;
}
#include <stdio.h>
int main(void) {
int index = -1;
int values[3] = {10, 20, 30};
int selected = -1;
if (index >= 0 && index < 3) {
selected = values[index];
}
printf("selected=%d\n", selected);
return 0;
}
#include <stdio.h>
int main(void) {
int index = 3;
int values[3] = {10, 20, 30};
int selected = -1;
if (index >= 0 && index < 3) {
selected = values[index];
}
printf("selected=%d\n", selected);
return 0;
}
index ← 1, values ← ⟨addr A⟩, selected ← -1
3int main(void) {4 int index→ 1 = 1; //@index=-1, 35 int values→ ⟨addr A⟩[3] = {10, 20, 30};6 int selected→ -1 = -1;selected ← 20
8if (index1 >= 0 && index < 3) {9 selected→ 20 = values[index]20;10}printf("selected=%d ", selected);
12 printf("selected=%d\n", selected20);13 return 0;14}outputselected=20
index ← -1, values ← ⟨addr A⟩, selected ← -1
3int main(void) {4 int index→ -1 = -1;5 int values→ ⟨addr A⟩[3] = {10, 20, 30};6 int selected→ -1 = -1;78 if (index >= 0 && index < 3) {9 selected = values[index];10 }1112 printf("selected=%d\n", selected-1);13 return 0;14}outputselected=-1
index ← 3, values ← ⟨addr A⟩, selected ← -1
3int main(void) {4 int index→ 3 = 3;5 int values→ ⟨addr A⟩[3] = {10, 20, 30};6 int selected→ -1 = -1;78 if (index >= 0 && index < 3) {9 selected = values[index];10 }1112 printf("selected=%d\n", selected-1);13 return 0;14}outputselected=-1