malloc: added functions to find and request memory

This commit is contained in:
Andrew Scott 2024-08-22 21:38:25 -04:00
parent ea7738bcf8
commit 620f779274
Signed by: a
GPG key ID: 7CD5A5977E4931C1
3 changed files with 76 additions and 1 deletions

View file

@ -1,7 +1,7 @@
CC = gcc
CFLAGS = -O3 -Wall -Wextra -Wpedantic
SRCS = main.c vm.c gc.c
SRCS = main.c vm.c gc.c galloc.c
OBJS = $(SRCS:.c=.o)
EXE = gc

49
gc_alloc.c Normal file
View file

@ -0,0 +1,49 @@
#include <stdio.h>
#include <unistd.h>
#include "gc_alloc.h"
static void *allocHead = NULL;
struct gcHeader *findFree(struct gcHeader **prev, size_t size) {
struct gcHeader *curr = allocHead;
while (curr && !(curr->free && curr->size >= size)) {
*prev = curr;
curr = curr->next;
}
return curr;
}
struct gcHeader *requestMem(struct gcHeader *prev, size_t size) {
struct gcHeader *block;
void *request;
block = sbrk(0);
if (block == (void *)-1) {
perror("sbrk block");
return NULL;
}
request = sbrk(size + sizeof(struct gcHeader));
if (request == (void *)-1) {
perror("sbrk request");
return NULL;
}
if ((void *)block != request) {
fprintf(stderr, "gcHeader: block != request");
return NULL;
}
if (prev) {
prev->next = block;
}
block->size = size;
block->next = NULL;
block->free = 0;
return block;
}

26
gc_alloc.h Normal file
View file

@ -0,0 +1,26 @@
#ifndef GALLOC_H
#define GALLOC_H
#include <stdio.h>
// Metadata for allocated memory - Headers are stored in a linked list to keep
// track of alloc's and free's
struct gcHeader {
size_t size;
int free;
struct gcHeader *next;
};
// Iterates over the galloc linked list attempting to find free space
struct gcHeader *findFree(struct gcHeader **prev, size_t size);
// Requests more memory from the kernel
struct gcHeader *requestMem(struct gcHeader *prev, size_t size);
// Performs allocations
void *galloc(size_t size);
// Frees memory allocated with galloc()
void gfree(void *ptr);
#endif /* GALLOC_H */