If it's ANSI-C (or supposed to be), the answer is never.
Doing so potentially hides a serious error, and gains you nothing. The error being a failure to include stdlib.h
malloc returns void*, and in C, void* to type* conversions are automatically handled by the compiler, so there's no need to help it by adding a redundant cast. This does NOT happen in C++.
Missing header file, compiled with a C compiler.
Code:
$ cat hello.c && gcc hello.c
#include <stdio.h>
/*#include <stdlib.h>*/
int main ( ) {
char *p = malloc( 10 );
free( p );
return 0;
}
hello.c: In function `main':
hello.c:4: warning: initialization makes pointer from integer without a cast
The fix here is to include the header file.
With header file, compiled with a C++ compiler
Code:
$ cat hello.c && gcc -xc++ hello.c
#include <stdio.h>
#include <stdlib.h>
int main ( ) {
char *p = malloc( 10 );
free( p );
return 0;
}
hello.c: In function `int main()':
hello.c:4: invalid conversion from `void*' to `char*'
- In short, you should be using the C++ allocators new and delete if you're writing C++ code.
- Or if you think it should be C anyway, figure out how to invoke your C compiler rather than your C++ compiler.
A common mistake is taking the default file type your IDE gives you (usually C++ it seems), and then trying to write 'C' code with it. Most people then blindly apply the cast because they're programming in the wrong language all of a sudden and do the simple thing just to make the compiler shut up.
The only time casting becomes necessary is if you're using some truly ancient compiler which pre-dates ANSI-C, and has 'prototyped' malloc as returning a char* (the original generic pointer type before void* came along).
--