FAQ > Casting malloc

Match word(s).

If you have any questions or comments,
please visit us on the Forums.

FAQ > Explanations of... > Casting malloc

This item was added on: 2003/03/14

Originally, the C language did not enjoy the void pointer. In those dark ages the char pointer was used as a generic pointer, so the definition of malloc looked something like this:

char *malloc(size)
int size;

Of course, this tended to cause problems when trying to assign a char pointer to, say, a double pointer. Because of this a cast was required:

double *p;
p = (double *)malloc ( n * sizeof ( double ) );

However, with the advent of the ISO C standard a new generic pointer was created, the void pointer. A void pointer can be assigned to any pointer type (except function pointers) safely and without the need for a cast. Thanks to this, the calls to malloc were simplified:

double *p;
p = malloc ( n * sizeof ( double ) );

However, many still prefer to cast malloc because they feel it makes the intentions of the memory allocation more clear. There is nothing wrong with this except in the event that stdlib.h, the header which declares malloc, is not included. If the return of malloc is cast then the error which would be flagged is hidden, resulting in a difficult to find bug. Also, during maintenance, if the type of the pointer changes but the cast is not changed, once again there is a difficult to find bug. The method most experienced programmers choose is:

p = malloc ( n * sizeof *p );

There is no cast for malloc since there is no need for one, and instead of using sizeof ( type ) to determine the size of the block, sizeof *ptr is used. By dereferencing the pointer and taking its size, the proper value is given without having to worry about modifying the allocation request if the type of the pointer changes.

So should you cast malloc? No, that is the preferred method. However, you should use whichever you like provided you are aware of the issues.

Credit: Prelude

Script provided by SmartCGIs