void* is compatible with any type no need for type casting.
The Function malloc
is most commonly used to attempt to ``grab'' a continuous portion of memory. It is defined by:
void *malloc(size_t number_of_bytes)
That is to say it returns a pointer of type void *
that is the start in memory of the reserved portion of size number_of_bytes
. If memory cannot be allocated a NULL
pointer is returned.
Since a void *
is returned the C standard states that this pointer can be converted to any type. The size_t
argument type is defined in stdlib.h
and is an unsigned type.
So:
char *cp;
cp = malloc(100);
attempts to get 100 bytes and assigns the start address to cp.
Also it is usual to use the sizeof()
function to specify the number of bytes:
int *ip;
ip = (int *) malloc(100*sizeof(int));
Some C compilers may require to cast the type of conversion. The (int *) means coercion to an integer pointer. Coercion to the correct pointer type is very important to ensure pointer arithmetic is performed correctly. I personally use it as a means of ensuring that I am totally correct in my coding and use cast all the time.
It is good practice to use sizeof()
even if you know the actual size you want -- it makes for device independent (portable) code.
sizeof
can be used to find the size of any data type, variable or structure. Simply supply one of these as an argument to the function.
reference:
http://users.cs.cf.ac.uk/Dave.Marshall/C/node11.html#SECTION001110000000000000000
see malloc specification in this link