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;
}