Malloc and Void Pointers

morcillo picture morcillo · Dec 25, 2012 · Viewed 24.2k times · Source

I'm studying this malloc function and I could use some help:

static void *malloc(int size)
  {
        void *p;

        if (size < 0)
                 error("Malloc error");
        if (!malloc_ptr)
                 malloc_ptr = free_mem_ptr;

        malloc_ptr = (malloc_ptr + 3) & ~3;     /* Align */

        p = (void *)malloc_ptr;
        malloc_ptr += size;

        if (free_mem_end_ptr && malloc_ptr >= free_mem_end_ptr)
                 error("Out of memory");

        malloc_count++;
        return p;
 }

I know that the malloc func allocates memory space for any type, if there is enough memory, but the lines i don't understand are:

p = (void *)malloc_ptr;
malloc_ptr += size;

How can it point to any data type like that? I just can't understand that void pointer or its location.

NOTE: malloc_ptr is an unsigned long

Answer

squiguy picture squiguy · Dec 25, 2012

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.