You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 3 Next »

With the introduction of void * pointers in the ANSI/ISO C Standard, explicitly casting the result of a call to malloc is no longer necessary and may even produce unexpected behavior if #include <stdlib.h> is forgotten.

Non-Compliant Code Example

If stdlib.h is not included, the compiler makes the assumption that malloc has a return type of int. When the result of a call to malloc is then explicitly cast to a pointer type, the compiler will assume that the cast from int to a pointer type is done with full knowledge of the possible outcomes. This may lead to behavior which is unexpected by the programmer.

char *p = (char *)malloc(10);

Compliant Solution

By ommiting the explicit cast to a pointer the compiler will realise that an int is attempting to be assigned to a pointer type and will generate a warning which may easily be corrected.

#include <stdlib.h>
...
char *p = malloc(10);

References

comp.lang.c FAQ list - Question 7.7 http://c-faq.com/malloc/cast.html
comp.lang.c FAQ list - Question 7.7b http://c-faq.com/malloc/mallocnocast.html

  • No labels