The first thing to say is that you use the malloc function to include stdlib.h (Cstdlib in C + +), not malloc.h. Because Malloc.h never appeared in C or C + + standards! So not all compilers have malloc.h this header file. But all C compilers should have stdlib.h this header file.
In C + +, the return value of the cast malloc () is required, otherwise it cannot be compiled. In C, however, this cast is redundant and is not conducive to code maintenance.
At first, C did not have a void pointer, when char* was used as a generic pointer (generic pointer), so malloc's return value was char* at that time. Therefore, the return value of malloc must be cast. Later, the ANSI C (i.e. C89) standard defines void pointers as new generic pointers. A void pointer can be assigned directly to any type of pointer (except for function pointers) without conversion. From then on, the return value of the malloc becomes void*, and there is no need to cast the malloc return value. The following program compiles correctly through VC6.
#include <stdlib.h>
int main( void )
{
double *p = malloc( sizeof *p ); /* 不推荐用 sizeof( double ) */
free(p);
return 0;
}
Of course, the cast malloc return value is not wrong, but the superfluous! For example, you might change double *p to int *p in the future. At this point, you will change all the related (double *) malloc (sizeof double) to (int *) malloc (int). If you change the leak, then your program is a bug. Even if you are sure to get rid of all the relevant statements, but this boring job you will not like it! You can avoid such problems without using a cast, and it's easy to write. Using the following code, no modifications are necessary, regardless of the type of pointer to be changed later.
Double *p = malloc (sizeof *p);
Similarly, you do not need to cast the return value if you use Calloc, realloc, and so on to return a function of void*.