C does not apply array bounds checking, so if you requested a space for 5 integers, you used more.
In fact, you overwrote 4 memory cells that really were not reserved for your specific purpose. Your program walked past the memory area that was allocated for your array, and began to store values ββin memory outside the allocated area.
The fact that this "worked" is just luck, and not what it depends on. It may work the next 100 times, or it may not work the next time it is tried, with the likely message "segmentation error."
Defensive programming, as you did, intelligently checking the return value of malloc, remembering that you are responsible for checking boundaries, compiling code with higher levels of warnings, etc. - here are some of your best defenses against such errors. Other tools like valgrind can also help check font types, but in the end it is up to you.
One of C's greatest strengths, its freedom to do all sorts of things, low and high, is also one of its IMO weaknesses. If Java is Volvo, C is probably more like a Ferrari with spotty breaks :)
Levon
source share