C Programming – Why Dynamic Memory Allocation Functions Return void*

cpointers

Consider the prototypes of C's dynamic allocation functions

malloc - void* malloc(size_t size);

calloc -  void* calloc(size_t n,size);

realloc - void* realloc(void* ptr,size_t newsize);

Now a statement like following

int* p=(int*)malloc(sizeof(int));

I know that casting to (int*) isn't needed in C since a void pointer can be assigned to a pointer variable of any object type, but why these functions by default not return fully typed pointer?. Wouln't it be nice if it returns int* instead of void pointer in this case? What is the reason void* is choosen as return type of these functions?

One other question: I've read here that in older C compilers the type of pointer returned by these functions was char* not void*. Is it true?

Best Answer

Because it can't.

How would it return a fully typed pointer? C doesn't have templates/generics, and it doesn't allow function overloading; let alone overloading by return type only. So there's no mechanism to have a malloc that knew what type you wanted.

I've read here that in older C compilers the type of pointer returned by these functions was char* not void*. Is it true?

In C, there is no byte. char is guaranteed to be a byte long, so char* is canonical "a pointer to some byte buffer", which is exactly what memory allocation functions want to return.

Related Topic