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
unsigned long(i.e.malloc_ptr) can also point to any other object, from an alignment point of view. This assumption is not always true (for example, on some systems it may not be able to point atlong doubleobjects). - Omri Barelfree_mem_ptrandfree_mem_end_ptrare initialized. It doesn't return NULL when there is no more space. If the functionerror()returns, then all hell breaks loose. - Jonathan Leffler