brk() exceeding the heap when implementing malloc()

312 Views Asked by At

I'm trying to implement my own version of the memory allocator malloc(). However I was pointed that in my case the brk() has exceeded the max heap.

I needed to run my code on a platform that does tests(so I can not see the tests).

This is my implementation of malloc():

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>


typedef struct obj_metadata {
    size_t size;
    struct obj_metadata *next;
    struct obj_metadata *prev;
    int is_free;
} obj_metadata;


void *mymalloc(size_t size)
{
    if (size == 0)
    {
        return NULL;
    }
    else
    {
        return sbrk(size * sizeof(obj_metadata));
    }
}

And I have got this error when testing:

Test "malloc-orders" exited with error: Assertion "addr <= heap + max_brk_size" at 
test_framework/intercept.c:38 failed: New brk 0x7fbe6f4c7fe0 beyond max heap size (max heap 
size=134217728, max heap=0x7fbe674c8000)

Can anybody tell me how can I fix this?

1

There are 1 best solutions below

0
Joshua On

I'm not too happy with that test harness but it does appear to be catching a real problem.

sbrk(size * sizeof(obj_metadata));

is clearly wrong after reading man sbrk. Consider doing

sbrk(size);

This too is technically wrong, because you ignored alignment. If the test harness actually catches this (most just don't), that should be fixed as so right at the top of mymalloc.

size_t align = size & (sizeof(obj_metadata) - 1);
if (align) size += sizeof(obj_metadata) - align;

Next you get to write the actual heap manager so both mumalloc() and myfree() work. Lots of work.