01 / 20

Handling Empty &
Boundary Cases

Learn to write robust C++ code that safely handles empty containers, out-of-range indices, and edge conditions that cause undefined behavior.

C++

What Are Boundary Cases?

A boundary case is an input at the extreme edge of what your code expects: the first element, the last element, an empty collection, or a size of zero. These are the inputs most likely to trigger bugs, crashes, and undefined behavior.

Empty Container
A vector, string, or array with zero elements
Index Extremes
Accessing index \( 0 \) or index \( n - 1 \) when the container may be empty
Off-by-One
Using index \( n \) instead of \( n - 1 \), reading one past the end

Why Boundary Safety Matters

In C++, accessing memory outside a container's bounds is undefined behavior: the compiler makes no guarantees. Your program might crash, return garbage, or appear to work until it silently corrupts data.

Valid Valid Valid ??? ??? [0] [1] [2] [3] [4] size() = 3 Undefined Behavior Memory layout of a vector with 3 elements

The Empty Container Problem

When a container has zero elements, there is no valid index at all. Even v[0] is undefined behavior. Many functions that seem safe: v.front(), v.back(), v[0]: will crash or corrupt memory on an empty container.

std::vector<int> v;  // empty vector

// ALL of these are undefined behavior:
int a = v[0];       // no element at index 0
int b = v.front();  // no first element
int c = v.back();   // no last element

The Golden Rule of Safe Access

Access element? !v.empty()? Yes
\( 0 \leq i < n \)
Yes Safe access No No Return / Handle

.at() vs operator[]

C++ gives you two ways to access elements by index. One is safe but slower; the other is fast but dangerous. Knowing the trade-off is essential.

v.at(i) v[i]
Bounds check Yes No
On bad index Throws std::out_of_range Undefined behavior
Performance Slight overhead Fastest
Best for User input, untrusted indices Hot loops after manual check

Key Boundary Patterns to Know

First Element
Check !v.empty() before v.front() or v[0]
Last Element
Check !v.empty() before v.back() or v[v.size()-1]
Loop Bounds
Use i < v.size(), never i <= v.size()
size() - 1 Trap
v.size()-1 wraps to a huge number when \( n = 0 \) because size() is unsigned

How to Apply Safe Access

1
Check emptiness first. Before any element access, test if (container.empty()) and handle it: return a default, throw, or skip.
2
Validate every index. Before container[i], verify 0 <= i < container.size(). For signed/unsigned mismatches, cast carefully.
3
Beware unsigned arithmetic. If size() is 0, then \(\text{container.size()} - 1\) underflows. Compare against 0 before subtracting.
4
Prefer range-based loops. for (auto& x : v) never goes out of bounds and naturally handles empty containers.
5
Use .at() for untrusted input. When the index comes from user input or computation, .at() throws a catchable exception instead of causing UB.

Example 1: Safe Front & Back

Write a function that returns the first and last element of a vector, or \( -1 \) if the vector is empty.

std::pair<int, int> getEnds(const std::vector<int>& v) {
    if (v.empty()) {
        return {-1, -1};  // safe fallback
    }
    return {v.front(), v.back()};
}

Example 2: The size() - 1 Trap

A common pattern iterates from \(0\) to \(n-1\) to compare adjacent elements. But watch what happens when the vector is empty:

// DANGEROUS: if v is empty, v.size()-1 wraps around!
for (size_t i = 0; i < v.size() - 1; i++) {
    if (v[i] > v[i + 1]) { /* ... */ }
}

// SAFE: check size first, or cast to int
for (int i = 0; i < (int)v.size() - 1; i++) {
    if (v[i] > v[i + 1]) { /* ... */ }
}

Example 3: Safe String Access

Strings are containers too. Checking for an empty string before accessing characters prevents the same class of bugs.

char firstChar(const std::string& s) {
    if (s.empty()) {
        return '\0';  // null character as sentinel
    }
    return s[0];
}

bool isPalindrome(const std::string& s) {
    if (s.size() <= 1) return true;  // empty or single char
    int lo = 0, hi = (int)s.size() - 1;
    while (lo < hi) {
        if (s[lo++] != s[hi--]) return false;
    }
    return true;
}

Example 4: Binary Search Boundaries

Binary search has a classic boundary bug: computing mid with \( \frac{lo + hi}{2} \) can overflow when both are large. And what if the array is empty?

int binarySearch(const std::vector<int>& v, int target) {
    if (v.empty()) return -1;  // boundary: empty

    int lo = 0, hi = (int)v.size() - 1;
    while (lo <= hi) {
        int mid = lo + (hi - lo) / 2;  // safe: no overflow
        if (v[mid] == target) return mid;
        if (v[mid] < target) lo = mid + 1;
        else hi = mid - 1;
    }
    return -1;
}

Boundary + Iterator Invalidation

Modifying a container while iterating over it can invalidate iterators, turning valid code into undefined behavior. This is a subtle boundary case.

// DANGEROUS: erasing during iteration
for (auto it = v.begin(); it != v.end(); ++it) {
    if (*it == 0) v.erase(it);  // invalidates it!
}

// SAFE: erase returns next valid iterator
for (auto it = v.begin(); it != v.end(); ) {
    if (*it == 0) it = v.erase(it);
    else ++it;
}

Common Mistakes

✕ Unsigned Underflow
Writing v.size()-1 when \( n = 0 \) wraps to a massive unsigned value. Cast to int or check size first.
✕ Off-by-One in Loops
Using i <= v.size() instead of i < v.size(). The last valid index is \( n - 1 \), not \( n \).
✕ No Empty Check
Calling front(), back(), or pop_back() on an empty container without checking first.
✕ Erasing During Iteration
Using erase() inside an iterator-based loop without capturing its return value invalidates the iterator and causes undefined behavior.
✕ Trusting User Input
Using a user-provided index with [] instead of .at(). Malicious input can read/write arbitrary memory.

Summary Cheat Sheet

Situation Dangerous Safe
First element v[0] !v.empty() ? v[0] : default
Last element v[v.size()-1] !v.empty() ? v.back() : default
Loop upper bound i <= v.size() i < v.size()
Adjacent comparison i < v.size()-1 i+1 < (int)v.size()
User-provided index v[userIdx] v.at(userIdx)
Midpoint calc \( \frac{lo+hi}{2} \) \( lo+\frac{hi-lo}{2} \)

Question 1 of 5

What happens when you call v.front() on an empty std::vector<int>?

Question 2 of 5

If v is an empty std::vector<int>, what is the value of v.size() - 1?

Question 3 of 5

Which loop condition is safe for comparing adjacent elements in a vector that might be empty?

Question 4 of 5

What is the key advantage of .at(i) over [i] for element access?

Question 5 of 5

What is wrong with this code?