1

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?

trincot
  • 317,000
  • 35
  • 244
  • 286
  • That error msg comes from your class test framework so it is difficult for us to know for sure what it means. Especially because you have not given us the full text of the requirements. But in general your allocation code looks wrong. You are increasing the heap size by multiple metadata blocks each time. Instead you should either by increasing the heap size by `size+sizeof(obj_metadata)` or better still, increasing the heap size by a fixed chunk only when needed with allocations coming from the chunks until the chunks can't satisfy an allocation request. – kaylum Nov 22 '20 at 03:33

1 Answers1

0

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.

Joshua
  • 40,822
  • 8
  • 72
  • 132