Difference between malloc and (int *)malloc in C
This question already has an answer here:
There is a difference; see here for a full discussion: Do I cast the result of malloc?
The most important point is that casting can hide an error if you forgot to #include <stdlib.h>
Without the cast, this is an error. With the cast, but without the include, C will assume that malloc()
returns an int
which may not be the same size as a pointer. In this case the return value of the real function will get chopped (if the pointer is longer than an int
, say, on a 64-bit machine) and lead to an invalid pointer.
malloc returns a void*
by default.
in the second case you are casting it to a int*
NOTE: in C you don't have to do the cast. That is, these two statements are 100% equivalent:
char *x = malloc(100);
char *y = (char *)malloc(100);
Conversions to and from void * are implicit in C.
malloc
returns a void *
which is okay since it is safe and automatic to convert a void *
to another pointer type. The second case needlessly casts the result of malloc
to an int *
and you should not cast the result of malloc
since it can hide error messages and is not necessary. For example if you forget to include stdlib.h
you should see a warning similar to:
initialization makes pointer from integer without a cast
since in many compilers malloc
will be implicitly declared to return int
.