Malloc and Void Pointers

The reason it returns a void pointer is because it has no idea what you are allocating space for in the malloc call. All it knows is the amount of space you requested. It is up to you or your compiler to decide what will fill the memory. The void pointer's location is typically implemented as a linked list to maintain integrity and know what values of memory are free which is surprisingly kept track of in the free function.


This is the implementation of malloc, so it is allowed to do things that would not be legitimate in a regular program. Specifically, it is making use of the implementation-defined conversion from unsigned long to void *. Program initialization sets malloc_ptr to the numeric address of a large block of unallocated memory. Then, when you ask for an allocation, malloc makes a pointer out of the current value of malloc_ptr and increases malloc_ptr by the number of bytes you asked for. That way, the next time you call malloc it will return a new pointer.

This is about the simplest possible implementation of malloc. Most notably, it appears not to ever reuse freed memory.


Malloc is returning a pointer for a chunk of completely unstructured, flat memory. The (void *) pointer means that it has no idea what it's pointing to (no structure), merely that it points to some memory of size size.

Outside of your call to malloc, you can then tell your program that this pointer has some structure. I.e., if you have a structure some_struct you can say: struct some_struct *pStruct = (struct some_struct *) malloc(sizeof(struct some_struct)).

See how malloc only knows the size of what it is going to allocate, but does not actually know it's structure? Your call to malloc is passing in no information about the structure, merely the size of how much memory to allocate.

This is C's way of being generic: malloc returns you a certain amount of memory and it's your job to cast it to the structured memory you need.