Possible Duplicates:
Do I cast the result of malloc?
Should I explicitly cast malloc()’s return value?
Hello,
gcc 4.4.4 c89
Normally I don’t cast the return result from a malloc call.
int *int_ptr = NULL;
int_ptr = malloc(sizeof(int));
However, I have read on here, that if you cast it can hide errors. How does it hide errors if you explicitly cast to an int?
int_ptr = (int*)malloc(sizeof(int));
Also, I was reading a c programming book that stated it was good programming practice to cast from a void pointer including a call from malloc.
Which would be good programming practice?
int *int_ptr = NULL;
void *ptr = NULL;
int_ptr = ptr;
or
int_ptr = (int*)ptr;
Many thanks for any advice,
It can hide the error of neglecting to include
stdlib.hbefore you callmalloc. Without the proper function declaration, the C compiler can assume that it returns anint, and an explicit cast will mask the fact that you’re not callingmallocproperly. See Q7.6 and Q7.16 from the comp.lang.c FAQ.There is no point to explicitly casting the result of
mallocin C. It potentially masks errors, and it increases the maintenance burden (if you ever decide to change the allocated type, you now have an extra site in the code that must be altered).The only time you should perform an explicit cast from
void*so is if you will be compiling your code as C++ since C++ does not allow that as an implicit cast. (But if you are writing C++ code, you should be usingstatic_castin this case.)