访问不存在的内存地址未触发Segfault,为何仅读取到垃圾值?
Great question—this is a classic C/C++ pitfall that cuts to the core of how memory is managed by compilers and operating systems. Let’s break down what’s happening:
1. Segfaults aren’t guaranteed for out-of-bounds access
A segmentation fault (segfault) only occurs when your program tries to access memory that the operating system has not mapped to your process. It’s not a check for "did I go past my array’s declared size"—it’s a low-level protection for memory that your program has no business touching at all.
As long as the out-of-bounds address you’re reading is still within the memory regions your process owns (like the stack or heap that’s already been allocated), the OS won’t intervene. You’ll just read whatever random data happens to be stored there—hence the "garbage values."
2. Your array is likely on the stack, which has extra unused space
If you declared double array[592] inside a function (the most common case), it lives on the call stack. The stack is a contiguous block of memory allocated to your process, and compilers/OSs don’t carve out exactly the minimum space needed for your variables:
- There’s often padding added for memory alignment (since
doublerequires 8-byte alignment, the compiler might round up the stack frame size to meet this requirement). - The stack also includes space for other local variables, function return addresses, saved register values, and even a small "guard" region at the bottom (but you haven’t hit that yet).
When you access array[592] and beyond, you’re just reading into this extra stack space—all of which is still part of your process’s memory, so no segfault is triggered.
3. You mixed up sizeof(array) with element count
Let’s clarify the root of your loop mistake:
sizeof(array)returns the total number of bytes in the array. For adoublearray of 592 elements, that’s592 * sizeof(double) = 592 * 8 = 4736bytes.- If your loop uses
i < sizeof(array), you’re iterating 4736 times, accessing indices from 0 to 4735—way beyond the array’s valid indices (0 to 591).
To get the correct element count, use either:
// C-style (works in all C++ versions) for (int i = 0; i < sizeof(array) / sizeof(array[0]); i++) { ... } // C++17 and later (safer, more readable) #include <iterator> for (int i = 0; i < std::size(array); i++) { ... }
4. When you would get a segfault
If you kept increasing the index far enough, you’d eventually hit:
- The end of your process’s stack region, where the OS places a non-writable "guard page" to catch stack overflow.
- A memory address that’s not mapped to your process at all (like another process’s memory or unused system memory).
At that point, the OS would send a SIGSEGV signal to your program, triggering a segfault. But in your case, you stopped just short of that boundary.
内容的提问来源于stack exchange,提问作者Blade

