The memory may or may not still contain a 4 when it gets to your cout line. It might contain a 4 strictly by accident. :)
First things first: your operating system can only detect memory access gone astray on page boundaries. So, if you're off by 4k or 8k or 16k or more. (Check /proc/self/maps
on a Linux system some day to see the memory layout of a process; any addresses in the listed ranges are allowed, any outside the listed ranges aren't allowed. Every modern OS on protected-memory CPUs will support a similar mechanism, so it'll be instructive even if you're just not that interested in Linux. I just know it is easy on Linux.) So, the OS can't help you when your data is so small.
Also, your int inf = 4;
might very well be stashed in the .rodata
, .data
or .text
segments of your program. Static variables may be stuffed into any of these sections (I have no idea how the compiler/linker decides; I consider it magic) and they will therefore be valid throughout the entire duration of the program. Check size /bin/sh
next time you are on a Unix system for an idea how much data gets put into which sections. (And check out readelf(1)
for way too much information. objdump(1)
if you're on older systems.)
If you change inf = 4
to inf = i
, then the storage will be allocated on the stack, and you stand a much better chance of having it get overwritten quickly.