I am trying to implement Malloc manually in a C project. Here is my code:
void *Mem_Alloc(int size) {
struct Node *p, *prevp = head;
if (fitPolicy == P_BESTFIT) {
}
if (fitPolicy == P_FIRSTFIT) {
for (p = prevp->next; ;prevp = p, p = p->next) {
if (p->size >= size) {
if (p->size == size)
prevp->next = p->next;
else {
p->size -= size;
p += p->size;
// p->size = size;
}
head = prevp;
return (void *)(p+1);
}
if (p == head) {
return NULL;
}
}
}
if (fitPolicy == P_WORSTFIT) {
}
return NULL;
}
Basically, I call mmap
in another method called Mem_Init
; then, the returned memory map is pointed to by the variable head
.
I always get a segmentation fault on the commented part in the middle of Mem_Alloc
. I do not know why. Could you guys help me with this? Some hints?