Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

shitalloc.c

Name: Anonymous 2009-02-02 2:34

I was bored, so I wrote an extremely shitty "memory allocator", if you could call it that.


#include <stdbool.h>
#include <stdlib.h>

typedef struct Node {
    bool   in_use;      // whether the node is in use.
    size_t size;        // the size of the node
    struct Node  *next; // the next node in the list.
} Node;

static Node *heap = NULL;

void shitalloc_init(size_t size)
{
    if((heap = malloc(size))) {
        heap->in_use = false;
        heap->size   = size - sizeof(Node);
        heap->next   = NULL;
    }
}

void shitalloc_cleanup()
{
    free(heap);
}

void *shitalloc(size_t size)
{
    Node *n = heap;
    void *ptr = NULL;
   
    // Look for a node that's not in use and that's big enough.
    while(n && (n->in_use || n->size < size))
        n = n->next;

    // If we've found a node that's too big, split it up.
    if(n && n->size > size) {
        Node *n2   = (void*)n + sizeof(Node) + size;
        n2->in_use = false;
        n2->size   = n->size - size - sizeof(Node);
        n2->next   = n->next;
        n->next    = n2;
        n->size    = size;
    }

    // If we've found a node, mark it as in-use and get the pointer.
    if(n) {
        n->in_use = true;
        ptr = (void*)n + sizeof(Node);
    }

    return ptr;
}

void shitfree(void *ptr)
{
    Node *n;

    if(ptr) {
        n = ptr - sizeof(Node);
        n->in_use = false;
    }
}

size_t shitused()
{
    Node *n;
    size_t size = 0;

    for(n = heap; n; n = n->next)
        size += sizeof(Node) + (n->in_use ? n->size : 0);

    return size;
}

Name: Anonymous 2009-02-02 8:35

mcurrent: dq START_OF_MEMORY
malloc:
    mov rax, [mcurrent]
    add [mcurrent], rdi
    ret


The one my kernel currently uses. I have another one that looks like OP's (except that it uses bit 63 for the bool, and next and length is the same thing), but it's currently horribly broken.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List