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
The “malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form.
Some Interesting Facts: 1) void pointers cannot be dereferenced. For example the following program doesn't compile.
We use the void pointers to overcome the issue of assigning separate values to different data types in a program. The pointer to void can be used in generic functions in C because it is capable of pointing to any data type.
The void pointer in C is a pointer which is not associated with any data types. It points to some data location in the storage means points to the address of variables. It is also called general purpose pointer. In C, malloc() and calloc() functions return void * or generic pointers. It has some limitations −
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With