An out-of-bounds write can silently corrupt adjacent data, causing a failure far from the defect and long after it was introduced. A spatial memory safety violation occurs when an access falls outside the valid boundaries of the object being accessed. The operation might crash, appear to work, or cause a security vulnerability. section 2.4.1 section 2.7
Listing 2.1 A spatial violation: writing beyond buffer bounds
#include <iostream>
int main() {
int buffer[10];
buffer[15] = 42; #A
int value = buffer[-1]; #B
std::cout << "Value: " << value << "\n"; #C
}A ten-element array is written at index 15 and read at index -1; both accesses are outside its bounds. section 2.4.1
In C++, these out-of-bounds accesses have undefined behavior. The same source can behave differently across platforms, compilers, or optimization levels, so an apparently successful run does not establish safety. section 2.4.1
Listing 2.2 Bounds checking to prevent spatial violations
#include <array>
#include <cstddef>
#include <iostream>
int main() {
std::array<int, 10> buffer{}; #1
std::size_t index = 15;
if (index < buffer.size()) { #2
buffer[index] = 42; #3
} else {
std::cerr << "Index " << index << " out of bounds\n"; #4
}
}An explicit check against buffer.size() prevents an invalid write and reports the rejected index. section 2.4.1
Using std::array and zero-initializing its elements does not by itself prevent an overflow: the standard does not require operator[] to check the index. Check bounds before access, including when using a fixed-size container. section 2.4.1
Spatial safety answers the “where” question; temporal safety asks whether the object is still alive when accessed. Both checks matter: a live buffer can be indexed out of bounds, and a freed buffer is unsafe to access at any index. section 2.4 section 2.4.3
Listing 2.5 Combining spatial and temporal checks
#include <cstddef>
#include <iostream>
#include <memory>
#include <optional>
class SensorBuffer {
public:
void activate(std::size_t size) {
buffer_ = std::make_unique<int[]>(size);
size_ = size;
for (std::size_t i = 0; i < size; ++i) {
buffer_[i] = static_cast<int>(i * 10);
}
}
void deactivate() {
buffer_.reset();
size_ = 0;
}
std::optional<int> readSensor(std::size_t index) {
if (!buffer_) {
return std::nullopt; #1
}
if (index >= size_) {
return std::nullopt; #2
}
return buffer_[index]; #3
}
private:
std::unique_ptr<int[]> buffer_;
std::size_t size_ = 0;
};A dynamically allocated buffer is checked for availability and bounds before a read; an invalid request returns std::nullopt. section 2.4.3
