When you write a[4]
, it is the same as writing *(a + 4)
. Since the compiler doesn't know how much memory is allocated at the address that a
points to, it will happily let you address the memory.
However, the memory located there could be anything - it could be another variable used by your program, part of the stack, or just out of the bounds of your program. Accessing outside the allocated space in this way is likely to (at best) produce a segmentation fault or (at worst) introduce a security hole by overwriting other parts of your program.
You are correct in that you can only assign to a[0]
or a[1]
safely, but the C compiler will let you assign outside that bounds (because it doesn't know any different).
It is not safe to do a[4]
in your example.
Also, it is better not to cast the result of malloc - see this answer