2

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()???

Vishwajeet Vishu
  • 492
  • 3
  • 16
Jayesh
  • 4,755
  • 9
  • 32
  • 62
  • 4
    `void` is *nothing*, but a *pointer* to `void` is still a pointer, it's just unspecified what kind of data it points to. –  Jul 03 '17 at 10:30

3 Answers3

6

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

void and void* are different. void means nohting but void* can be anything. A pointer of void (void*) can be casted into any other pointers.

Why malloc() return void*?

It means malloc allocated a memory buffer for you and you can use it to store anything you want.

Dang Huynh
  • 102
  • 3
1

Try not to get confused by the white space. In C, you should read declarations this way:

int *i; is to be read as - the variable *i which gives an int or the variable i which is a pointer to an int. Same goes for functions. Something like void *fun() means fun is a function which returns a pointer to a void. Check this for a more complete answer.

babon
  • 3,615
  • 2
  • 20
  • 20