Malloc and array index confusion in C

C doesn't enforce any array bounds checking, so while you requested space for 5 integers, you used more.

In fact you overwrote 4 memory locations that really weren't set aside for your specific purpose. Your program went past the area in memory that was set aside for your array, and started to store values in memory outside the allocated region.

The fact that this "worked" is just pure luck and not something to be dependent on. It may work the next 100 times, or it may fail the next time you try it, with most likely a "segmentation fault" message.

Defensive programming, like you did by sensibly checking the return value of malloc, being mindful that you are responsible for bounds checking, compiling code with high warning levels enabled, etc are some of your best defenses to guard against these sort of errors. Other tools, such as valgrind, lint type checkers can also help, but at the end it's up to you.

One of C's greatest strengths, its freedom to do all sorts of things, low and high-level, is also one of its greatest weaknesses IMO. If Java is a Volvo, C is perhaps more like a Ferrari with spotty breaks at times :)

Tags:

C

Arrays

Malloc