Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the intention/benefit of malloc returning type void *?

Knowing more C++ than C I wondered if someone could explain the reason why malloc() always returns a pointer of type void, rather than malloc having been implemented with some mechanism which allows it to return a pointer of the type the user passed in? It just seems a little "hacky" constantly explicitly casting the returned void pointer to the type you want.

like image 233
user997112 Avatar asked Oct 27 '25 05:10

user997112


1 Answers

Well, in C you don't have to do the cast, so your point is moot. That is, these two statements are 100% equivalent:

 char *x = malloc(100);
 char *y = (char *)malloc(100);

Conversions to and from void * are implicit in C. So, to address your question, the very reason malloc returns void * is so that you don't have to cast.

Besides that, in C there's no way to pass type information around, so doing something like:

 char *x = malloc(100, char);

is not possible.

If you're in C++, the cast is necessary, but you shouldn't be using malloc anyway - that's what new is for, and it does handle the type information correctly.

like image 119
Carl Norum Avatar answered Oct 29 '25 18:10

Carl Norum