0

Why do so many C functions have Void return types but do not return nothing, for example I was looking at the man page for malloc and it return type is Void, but it also says returns an adress to where it has size_t bytes allocated.

void * malloc(size_t  n)

The malloc() functions allocates size bytes and returns a pointer to the allocated memory.

How does casting work in these cases?

Also what does it mean to have type void in a parameter?

The free function has type void.

void free(void *ptr)
J. Doe
  • 9
  • 2
  • This might be related: https://stackoverflow.com/questions/11626786/what-does-void-mean-and-how-to-use-it – Owen Apr 19 '18 at 02:28
  • 2
    don't confuse `void *` and `void`, one mean pointer to something, other mean nothing. Now you asking the question, I'm like... yes in fact it's very misleading ! – Stargateur Apr 19 '18 at 02:29
  • "How does casting work in these cases?" => [Do I cast the result of malloc?](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc?rq=1) – Stargateur Apr 19 '18 at 02:36

1 Answers1

1

malloc() does not return void but void *. this is a "magic" type in C, because it can be converted into other types of pointer. For function like malloc(), only the caller knows what types he will use, so malloc() doesn't have to also cannot define the return type. As an alternative, it returns the type of void *.

Same reason for the function free() which has *void *ptr as its parameter.

Stargateur
  • 24,473
  • 8
  • 65
  • 91
TongyuYue
  • 11
  • 2