In this question, someone suggested in a comment that I should not cast the result of malloc. i.e., I should do this:
malloc
int *sieve = malloc(sizeof(*sieve) * length);
rather than:
int *sieve = (int *) malloc(sizeof(*sieve) * length);
Why would this be the case?
In C, it’s generally recommended not to cast the result of malloc for several reasons:
void*
sieve
// Later in the code, if you change the type of 'sieve': sieve = (float*)malloc(sizeof(*sieve) * length); // Need to update the cast here too
It’s worth noting that this advice applies to C, and in C, the situation is a bit different. In C, the result of malloc is automatically converted to the appropriate pointer type, but some developers still prefer to use a cast for consistency or to indicate that dynamic memory allocation is taking place. However, it’s generally considered more idiomatic in C++ to avoid the cast.