I read this comment under a StackOverflow answer (https://stackoverflow.com/a/3331268/17342809):
Memory allocation requests should be made as type-independent as possible: no cast on the result of memory allocation function and no type names under the sizeof. The strange habit of using type names under sizeof in malloc requests (and such) has long ago earned its place in the garbage bin of C programming. Type names belong in declarations. If it is not a declaration, type names are not allowed (as much as possible).
I can understand why it is bad to cast the result of malloc()
(by reading this answer to another question: https://stackoverflow.com/a/605858/17342809). However, it looks to me that using type names in sizeof() (e.g. sizeof(int *)
instead of sizeof(void *)
) in memory allocation should make your code easier to read, as the reader could immediately see what you intend to use this memory for.
Can someone explain me why it is a bad habit to use explicit pointer types in malloc(sizeof(type *))
?
Instead of calling sizeof
with the type prefer to use the variable name. For example instead of:
int *foo = malloc(sizeof(int));
prefer the idiom:
int *foo = malloc(sizeof *foo);
This means you are not repeating (DRY) the type of the declaration which may change independently. If the type changes in best case it doesn't matter or you allocate too much memory, worst case you allocate too little memory which cause corrupting due to a change that is possible far away (say, in a separate header file).
The other thing I find convenient is that it's a purely mechanical transformation (as in I don't have to think about it): sizeof
followed by *
and the name of the variable. This eliminates the class of errors where the wrong type is used.
It's usually shorter to write.
Parenthesis are required when you pass a type of sizeof
but not if you pass a variable. sizeof
binds the way you expect so sizeof *foo * 42
would allocate space for 42 int
s as expected.