小能豆

Should I cast the result of malloc?

javascript

In this question, someone suggested in a comment that I should not cast the result of malloc. i.e., I should do this:

int *sieve = malloc(sizeof(*sieve) * length);

rather than:

int *sieve = (int *) malloc(sizeof(*sieve) * length);

Why would this be the case?


阅读 229

收藏
2023-12-29

共1个答案

小能豆

In C, it’s generally recommended not to cast the result of malloc for several reasons:

  1. Avoid Redundancy: The type of the pointer returned by malloc is void*. In C, there’s an implicit conversion from void* to any other pointer type. Casting the result of malloc is considered redundant because the conversion is automatic.

int *sieve = malloc(sizeof(*sieve) * length);

  1. Avoid Bugs: If you cast the result, and later you decide to change the type of sieve, you would need to update the cast in every place it’s used. This can lead to bugs if you forget to update the cast in some locations.

// Later in the code, if you change the type of 'sieve': sieve = (float*)malloc(sizeof(*sieve) * length); // Need to update the cast here too

  1. Readability: Omitting the cast often makes the code cleaner and more readable. The explicit cast doesn’t provide any additional type safety or error checking.

int *sieve = malloc(sizeof(*sieve) * length);

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.

2023-12-29