Daniel's Professional Blog

C does not check anything for you

I implemented a program in C that finds Nth Primary Number.

It worked ideally until 28th number and went to endless loop from number 29.

The reason of the bug was the following. In C, array values are not initialized. Every array item has the value of whatever is put in that part of memory at the moment. I expected an integer array to have items of value 0 each. That was not the case. The moral of the story, you have to initialize every array item manually, like this:

for (i=1; i<term; i++) {
    prime_list[i] = 0;
}

There is even more interesting part. You can assign a value to an array item of index beyond the array length. (E.g. prime_list has length 3, but you can still do prime_list[5] = 11.) C will not complain and stop you. It will write the value you provide to the corresponding part of the memory, as if an array were really that large. That part of the memory could even be outside of the C program. You have a good chance to ruin not only the C program when you run it, but any random thing in the OS. This is WILD!

#C