Return type of malloc

31.12.12
int *ptr = malloc(sizeof(int)*length);
int *ptr = (int *)malloc(sizeof(int)*length);
Which one is correct?
Its the first one. You don't cast the result, since:
It is unnecessary, as void * is automatically and safely promoted to any other
pointer type in this case.

It can hide an error, if you forgot to include <stdlib.h>. 
This can cause crashes, in the worst case.

It adds clutter to the code, casts are not very easy to read (especially if the pointer type is long).

It makes you repeat yourself, which is generally bad.
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 changes for straight C, not C++. I very firmly believe in C and C++ as separate languages.

No comments:

Post a Comment