In C, a lot of wrong and "wrong" things don't display error messages from the compiler. In fact, you may not even see error messagens when you run the program -- but another person running your program in a different computer may see the error.
One important concept in C is called undefined behavior. To put it in simple terms, it means that the behavior of your program is unpredictable, but you can read more about this subject in this question: Undefined, unspecified and implementation-defined behavior.
Your program is undefined for a two reasons:
- When either
size
or nmemb
is zero, calloc()
may return NULL
. Your program is not checking the output of calloc()
, so there's a good chance that when you do test[i]
you are attempting to derreference a NULL
pointer -- you should always check the result of calloc()
and malloc()
.
- When you call
malloc()
or calloc()
, you are essentialy allocating dynamic memory for an array. You can use your pointer to access the elements of the array. But you can't access anything past the array. That is, if you allocate n
elements you should not try to access the n+1
-th element -- nether for reading.
Both items above make your program invoke undefined behavior. There might also be something undefined about accessing an empty object other than item #2 listed above, but I'm unsure.
You should always be careful about undefined behavior because, when your program invokes UB, it is essentialy unpredictable. You could see a compilation error, the program could give an error messagen, it could run successfuly without any problems or it could wipe out every single file in your hard disk.