之前在Stack OverFlow上贴了段代码,求帮忙找bug,意外的收获了关于malloc()前是否需要类型转换的一些说法,很涨姿势,贴出来大家共享
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 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.
- It can hide an error, if you forgot to include<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. Note: as of C11 implicit functions are gone from C, and this point is no longer relevant since there’s no automatic assumption that undeclared functions return int.
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.