So, I have this purpose for implementing my own malloc and free in C. The problem is one of the requirements for the function memory_free(void *ptr). It should return 1 if the pointer is invalid, i.e. It has not been allocated, memory_alloc(unsigned int size)or otherwise returns 0. I simply cannot figure out how to do this without being completely ineffective.
So, my memory structure is this: I have a global pointer to the beginning of the array, which I get as a heap. Each memory block has a header intto report its size and free it.
This is my memory_free (void * ptr) function right now, TYPE typedef unsigned int:
int memory_free(void *ptr)
{
void *head = ptr;
if (head == NULL)
return 1;
head -= sizeof(TYPE);
if (!((*(TYPE*) head) & 1 ))
return 1;
(*(TYPE*) head) &= ~0x1;
return 0;
}
ptr , , , 4 . - , , . - ?