Question

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?

Was it helpful?

Solution

ughoavgfhw has the right direction, but casting lvalue is not appropriate.

You can use:

void * tmp_p = (void *)p;
tmp_p += p->size;
p = (struct Node *)tmp_p;

OTHER TIPS

It's impossible to tell for sure, but this is most likely because you are expecting p += p->size to increment p by p->size bytes. In reality, this would increment it by p->size times the size of *p. If the size you are trying to allocate is less than half the size of the memory you have available, this would move the pointer past the end even if *p is only 2 bytes.

To fix this, you should cast your pointer to a character pointer for the addition.

((char*)p) += p->size;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top