In C, When you access array with out of bound index, according to C language, the behavior is undefined, Since C/C++ doesn't actually do any boudary checking with regards to arrays. It only depends on the OS to ensure that you are accessing valid memory.
Why you does not see an error
In short, you are lucky.
Usually arrays are allocated in adjacent memory address. When you add your pointer, compiler will simply generate code to access the adjacent memory. Since it is still in your program's memory space, Operating System does not trigger error for this.
How to check such kind of error
There are some tools, like valgrind, and also some helpful compiler flags which could be used to detect some of these errors.
For example, if you run the generated binary in valgrind
, valgrind
will generate following messages when write to p[10]
==14590== Invalid write of size 1
==14590== at 0x4005B2: main (in /home/lingkun/Develop/courage/cpp/src/a.out)
==14590== Address 0x520204a is 0 bytes after a block of size 10 alloc'd
==14590== at 0x4C2BBA0: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==14590== by 0x400597: main (in /home/lingkun/Develop/courage/cpp/src/a.out)
==14590==
==14590== Invalid read of size 1
==14590== at 0x4005C2: main (in /home/lingkun/Develop/courage/cpp/src/a.out)
==14590== Address 0x520204a is 0 bytes after a block of size 10 alloc'd
==14590== at 0x4C2BBA0: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==14590== by 0x400597: main (in /home/lingkun/Develop/courage/cpp/src/a.out)
==14590==
INDEX:10 c
INDEX:11 c
INDEX:12 c
INDEX:13 c
INDEX:14 c