In this question, someone suggested in a comment that I should not cast the results of
int *sieve = malloc(sizeof(int)*length);
int *sieve = (int *)malloc(sizeof(int)*length);
No; you don't cast the result, since:
void *is automatically and safely promoted to any other pointer type in this case.
<stdlib.h>. This can cause crashes (or, worse, not cause a crash until way later in some totally different part of the code). Consider what happens if pointers and integers are differently sized; then you're hiding a warning by casting and might lose bits of your returned address.
As a clarification, note that I said "you don't cast", not "you don't need to cast". In my opinion, it's a failure to include the cast, even if you got it right. There are simply no benefits to doing it, but a bunch of potential risks, and including the cast indicates that you don't know about the risks.
Also note, as commentators point out, that the above talks about straight C, not C++. I very firmly believe in C and C++ as separate languages.
To add further, your code needlessly repeats the type information (
int) which can cause errors. It's better to dereference the pointer being used to store the return value, to "lock" the two together:
int *sieve = malloc(length * sizeof *sieve);
This also moves the
length to the front for increased visibility, and drops the redundant parentheses with
sizeof; they are only needed when the argument is a type name. Many people seem to not know (or ignore) this, which makes their code more verbose. Remember:
sizeof is not a function! :)