Tuesday, February 14, 2012

What is malloc()?

The malloc() function allocates specified no. of bytes and returns a pointer to the allocated memory. The memory is not initialized. If specified size is zero, then malloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().

void *malloc(size_t size)

The malloc() returns void pointer on success, which can be assigned to any pointer variable by type casting. on failure it returns NULL.

char *ptr;
ptr = (char *)malloc(10*sizeof(char));

In the above code, declared char pointer ptr and dynamically allocated 10 bytes using malloc(). malloc will returns void pointer, we need char pointer so type casting it into char pointer. And in the function call we multiplied the size with sizeof operator. this is for aligning the the no.of bytes for the data type basing on the machine.

No comments:

Popular Posts