Out-of-Bounds Array Access: Why It Sometimes Seems to Work
Reading or writing past the end of a C array is undefined, yet it often runs without a crash. See where the extra bytes come from and why that luck is a trap.

You declare an array of three integers, write to the fourth element by mistake, and the program runs to the end without a single complaint. Maybe it even prints the right thing. A beginner reasonably concludes that C is forgiving. The truth is closer to the opposite: C is not checking, so nothing stops the access, and whether anything goes wrong depends on what happens to be sitting in the memory next door. This post explains where the "extra" bytes come from, why a program can survive an out-of-bounds access today and fail tomorrow, and how to make the bug visible. The examples use C17, GCC 14 and glibc 2.40 on 64-bit Linux.
What the rule says
An array of n elements has valid indexes 0 through n - 1. Forming the address one past the end is allowed, so you can write a loop that stops when a pointer equals that address, but you may not read or write through it. Anything beyond that, such as a[n + 1] or a[-1], is undefined behavior under C11 6.5.6p8. The standard does not say "the program crashes" or "the program reads a garbage value". It says nothing at all about what happens, as the earlier post on undefined behavior explains.
The compiler is not required to check the index, and normally does not. When you write a[i], the generated code computes the address a + i * sizeof(a[0]) and accesses it. If i is out of range, the address is simply a different address, and the hardware accesses whatever lives there.
So the question becomes: what lives there? The answer depends on where the array is stored, and the rest of this post goes through the cases.
Case 1: a neighbor inside a struct
Memory inside a struct is laid out in declaration order, with no gaps when types match. An array's neighbor is therefore the next member.
#include <stdio.h>
struct pair {
int arr[3];
int after;
};
int main(void) {
struct pair p = { {1, 2, 3}, 42 };
printf("p.arr[3] = %d\n", p.arr[3]); // out of bounds
return 0;
}On a typical x86-64 Linux build at -O0, the member after sits right behind arr, so the program prints:
p.arr[3] = 42The read "worked": it returned the value of a different member, and the value looked sensible, which makes it more dangerous than a crash. GCC at -O2 may warn with -Warray-bounds and is free to compile the access differently, so the same source can print something else with another flag. The output above is what you would typically see, not something the language promises.
A write through the same index does damage in silence. Assigning p.arr[3] = 99 would overwrite after, and the later code that reads after sees 99 without any visible cause.
Case 2: a neighbor on the stack
Local arrays live on the stack next to other locals, saved registers and the return address. The compiler decides the order, and it changes with the optimization level, the compiler version and even the function's other variables.
#include <stdio.h>
int main(void) {
int guard = 7;
int arr[3] = {1, 2, 3};
for (int i = 0; i <= 3; i++) { // off by one: should be i < 3
printf("arr[%d] = %d\n", i, arr[i]);
}
printf("guard = %d\n", guard);
return 0;
}A typical result at -O0 is:
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 7
guard = 7Here guard happened to be placed right after arr, so the fourth read shows its value. On another layout the same read could show a saved register, a stale value from an earlier call or the stack protector's canary, and the number would be different on every run if address space randomization affects it. The loop condition i <= 3 is the classic off-by-one: the author meant "less than the length".
If a loop like this writes instead of reads, it corrupts the neighbor, and when the neighbor is a saved return address it hands control of the program to whoever controls the written value. That is how stack buffer overflow exploits work.
Case 3: slack inside a heap block
Memory from malloc is rounded up. On 64-bit glibc, the allocator hands out chunks whose usable size is a multiple of 16 bytes, minus 8 for a header, with a minimum of 24 usable bytes. You can see it with malloc_usable_size, a glibc extension declared in <malloc.h>:
#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char *buf = malloc(10);
if (!buf) return 1;
printf("requested 10, usable %zu\n", malloc_usable_size(buf));
free(buf);
return 0;
}requested 10, usable 24You asked for 10 bytes and the allocator owns 24, so writing buf[10] through buf[23] lands in memory that belongs to your block. Nothing crashes, nothing is corrupted, and the bug is invisible. But the language-level allocation is still 10 bytes. The usable size is an implementation detail that can change with the allocator, the version or the platform, and a program that depends on it breaks the day you link a different allocator. Write buf[24] and you cross into the next chunk's header, which the allocator uses to track free memory. The crash then comes later, inside free or malloc, nowhere near the faulty line.
Case 4: the page that is already there
Even when the array has no neighbor you can name, the operating system maps memory in whole pages, 4096 bytes on most x86-64 systems. A global or stack array that ends mid-page leaves the rest of the page mapped and readable, so a read past the end of the array fails only when the address finally crosses into an unmapped page. A read that is a few bytes too far succeeds. A read that is a few thousand bytes too far may crash. The line between the two has nothing to do with the array.
Why "it works" is a trap
Put the four cases together and a pattern appears. An out-of-bounds access seems harmless when the bytes it touches are mapped and happen to be unimportant. All of the following can change that without any edit to the faulty line:
another compiler or optimization level that reorders variables,
a new local variable added earlier in the function,
a different allocator or a different
malloccall history,a hardening feature such as a stack protector, which changes the layout,
a different input that makes the index larger by one more element.
The bug is real the whole time. It is the evidence that goes away.
On top of that, the compiler may use the undefined access to reason about the program. If it can prove i is 3 on a path and the array has 3 elements, it may conclude the path is unreachable and remove it, and loops like for (i = 0; i <= 3; i++) arr[i] = 0; have been compiled into infinite loops for that reason.
Making the bug visible
Three tools turn silent out-of-bounds access into a clear report.
Compiler warnings. GCC's -Wall -O2 enables -Warray-bounds, which catches constant indexes like p.arr[3]. Set -Warray-bounds=2 for a stricter check. It cannot see an index computed at run time.
AddressSanitizer. Build with -fsanitize=address -g and the program stops at the first bad access with the exact location. For a write one byte past a 10-byte heap block, the report looks like this:
==3190==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x60200000001a at pc 0x5628f3a1c1d8 bp 0x7ffc8e5c4e50 sp 0x7ffc8e5c4e40
WRITE of size 1 at 0x60200000001a thread T0
#0 0x5628f3a1c1d7 in main slack.c:8
0x60200000001a is located 0 bytes after 10-byte region [0x602000000010,0x60200000001a)The addresses and process id differ per run. The important parts are the line "0 bytes after 10-byte region", which tells you the access is exactly one past the end, and the source line. AddressSanitizer surrounds each allocation with poisoned red zones and checks every access, so it catches the write at buf[10] even though the allocator has 24 usable bytes.
UndefinedBehaviorSanitizer. With -fsanitize=bounds (included in -fsanitize=undefined), accesses to arrays whose size the compiler knows print index 3 out of bounds for type 'int [3]'.
Use both together in your tests, and keep a habit of running new code under them before you trust it.
How to avoid it by construction
Write loops with the length, not with a hard-coded number: for (size_t i = 0; i < sizeof arr / sizeof arr[0]; i++). Keep each pointer paired with its length, and pass both. Prefer snprintf over sprintf, fgets over gets and strnlen over strlen on untrusted data. And when you can, use a language feature that checks for you, such as bounds-checked slices in Rust and Zig, accepting the small cost.


