1. 程式人生 > >關於malloc()前是否需要型別轉換,即void*轉換為具體型別

關於malloc()前是否需要型別轉換,即void*轉換為具體型別

之前在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.