malloc: defined get_next_chunk, get_prev_chunk, and align

This commit is contained in:
Andrew Scott 2024-09-18 02:02:44 -04:00
parent f80156344b
commit 37d5cfd532
Signed by: a
GPG key ID: 7CD5A5977E4931C1
2 changed files with 39 additions and 1 deletions

View file

@ -12,7 +12,7 @@
#define MIN 3 /* Minimum number of 8-byte segments for data in a chunk */
/*
* Metadata for allocated memory
* Metadata and user data for allocated memory
*
* footer: user data for previous chunk
* size: size of chunk in bytes
@ -30,6 +30,18 @@ struct gc_chunk {
struct gc_chunk *prev;
};
// Gets a pointer to the next chunk
struct gc_chunk *get_next_chunk(struct gc_chunk *curr);
// Gets a pointer to the previous chunk, ensuring that current can be coalesced
struct gc_chunk *get_prev_chunk(struct gc_chunk *curr);
// Updates chunk footer information
void set_footer(struct gc_chunk *curr);
// Gets footer information for the current chunk
int get_footer(struct gc_chunk *curr);
// Performs allocations of SIZE bytes
void *gc_malloc(size_t size);

View file

@ -1,4 +1,5 @@
#include <assert.h>
#include <stdint.h>
#include <sys/mman.h>
#include "gc_malloc.h"
@ -14,3 +15,28 @@ static inline struct gc_chunk *magic(void *mem)
{
return (struct gc_chunk *)((uint64_t *)mem - MAGIC);
}
// Aligns the amount of memory requested by the user with chunk size
static inline size_t align(size_t size)
{
const size_t alignment = 8;
size = (size + (alignment - 1)) & ~(alignment - 1);
if (size <= MIN)
return MIN;
else
return size;
}
struct gc_chunk *get_next_chunk(struct gc_chunk *curr)
{
unsigned size = curr->size;
return (struct gc_chunk *)((uint64_t *)curr + MAGIC + (size - 1));
}
struct gc_chunk *get_prev_chunk(struct gc_chunk *curr)
{
assert(curr->merge);
unsigned size = curr->footer;
return (struct gc_chunk *)((uint64_t *)curr - (size - 1) - MAGIC);
}