Search code examples
cfunctionmallocvoidcalloc

Confusion about malloc and calloc function in C


Declaration of malloc function:

void *malloc(size_t size);

Here, malloc returns void pointer. So, A void function returns nothing, then

Why we assign malloc(function call) value to pointer?

For example:

int *ptr;
ptr = malloc(10 * sizeof (*ptr));
^^^

What does return value holds from malloc()???


Solution

  • This was probably an unfortunate choice on the part of language designers, but they decided to reuse void for their void* construct, which nearly reverses its meaning: while void means "returns nothing", void* means "return a pointer to anything."

    Essentially, void* is a pointer to an unspecified object. It must be converted to a pointer to a specific type before you dereference it. That is precisely the kind of pointer returned by malloc or calloc.