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.
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.
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.
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
.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
How to Apply Safe Access
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
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
Consider this function:
void removeZeros(std::vector<int>& v) {
for (auto it = v.begin(); it != v.end(); ++it) {
if (*it == 0) {
v.erase(it);
}
}
}
What is wrong with this code?