HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

My own malloc() function in C

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
mallocownfunction

Problem

Is this acceptable? What is the next step to improve algorithm and make them more clear and faster?

typedef struct heap_block
{  
    struct heap_block* next;
    size_t size;
    bool isfree;
    int x; // for alligment
}header;

#define Heap_Capacity 16777216
unsigned long long active_size;  // # bytes in active allocations

static uint64_t heap[Heap_Capacity/sizeof(uint64_t)];

static char* max_heap =(char*)(&heap[0]);
static char* min_heap = (char*)(&heap[0]);
static char *END_CHK = "\xDE\xAD\xC0\xDA";
header* last_allocated;

void* malloc(size_t sz) 
{
    if(sz == 0 || sz > Heap_Capacity)
    {
        return NULL;
    }

    header* block = (header*)heap;
    if(active_size == 0)
    {
        set_data_to_block(block, sz);
        return (void*)last_allocated;
    }

    while(block->next != NULL)
    {
        block = block->next;
    }

    block->next = (header*)((char*)to_end_data(block) + 8);
    header* new_block = block->next;
    set_data_to_block(new_block, sz);

    return (void*)last_allocated;
}

void set_data_to_block(header* block, size_t sz)
{
    block->size = sz;
    block->isfree = false;
    block->next = NULL;

    active_size += sz;
    last_allocated = block + 1;
    char* end_of_data_block = (char*)to_end_data(block);

    if(max_heap size);
}

Solution

-
Avoid globals

last_allocated is only used to communicate the result of set_data_to_block back to malloc. Returning the result is much cleaner.

-
Avoid special cases

There is no need to special case the initial allocation. If you do not want to rely on ((header *) heap)->next == NULL initially, you may want to provide an initialization method (which I recommend anyway).

Context

StackExchange Code Review Q#88552, answer score: 7

Revisions (0)

No revisions yet.