Today I reached page 167 of The C Programming Language (second edition Brian W. Kernighan & Dennis M. Ritchie) and found that the author says I must cast malloc
. Here is the part from the book:
7.8.5 Storage Management
The functions malloc and calloc obtain blocks of memory dynamically.
void *malloc(size_t n)
returns a pointer to n bytes of uninitialized storage, or NULL if the request cannot be satisfied.
void *calloc(size_t n, size_t size)
returns a pointer to enough free space for an array of n objects of the specified size, or NULL if the request cannot be satisfied. The storage is initialized to zero. The pointer returned by malloc or calloc has the proper alignment for the object in question, but it must be cast into the appropriate type, as in
int *ip; ip = (int *) calloc(n, sizeof(int));
I already know that malloc
(and its family) returns type void*, and there are good explanations why not to cast malloc
.
But my question is: Why does the book say I should cast it?