malloc() function is used to allocate a block of memory in the heap. It allocates the user a specified number of bytes but does not initialize. Once allocated, the program accesses this block of memory via a pointer that
size parameter is of type
The default pointer returned by
malloc() is of the type
void but can be cast into a pointer of any data type. However, if the space is insufficient for the amount of memory requested by
malloc(), then the allocation fails and a
NULL pointer is returned.
The following example showcases the
int *ptr;// The pointer ptr holds the address of the first byte in the allocated memoryptr = (int*) malloc(5 * sizeof(int));
Since the size of
int is 4 bytes, the above statement will allocate 20 bytes (4 * 5) of memory.