Skip to content

taurasbear/c-buddy-memory-alloc

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

26 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Custom Memory Allocator inspired by the Buddy System

An educational project written in C

This project includes allocate_memory and free_memory functions similar to the standard library's malloc and free. Before allocating memory, the allocator must be initialized with initialize_memory_allocator.

Key Points

  • Memory is allocated in static memory (not the heap)
  • This is not a true Buddy System implementation1

Example code

initialize_memory_allocator();

// Allocating memory for 5 int elements
int *a = allocate_memory(sizeof(int) * 5);

// Initializing dynamic array with data
for (int i = 0; i < 5; i++)
{
    a[i] = i;
}

// Printing dynamic array values
for (int i = 0; i < 5; i++)
{
    printf("Value at index %d: %d\n", i, a[i]);
}

// Freeing after use
free_memory(a);

Free memory Structure

The following code example would produce a binary tree structure as shown below:

// in this example 
// sizeof(BlockHeader) = 24
// MEMORY_POOL_SIZE = 1024

initialize_memory_allocator();

int *a = allocate_memory(214);

alt text

The actual block size in this implementation is smaller than expected because each block must include not only the free memory space but also the metadata of the BlockHeader struct2. This metadata is essential for navigating the binary tree.

Additional Information

Footnotes

  1. While this project is inspired by the Buddy System, it does not implement a true Buddy System because a true Buddy System's block size must be a power of two.

  2. In order to have a true Buddy System structure, the metadata of the struct would need to be stored elsewhere.

About

Custom Memory Allocator inspired by the Buddy System

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages