2

I need to make a self made malloc simplified a bit. The memory pool is just an array of unsigned chars. I'm planning on having a struct that is a header, containing the size of the memory block, a flag ('A' for allocated, 'F' for free) and a pointer to the next header (though I guess this isn't necessary because you already have the length of the block)

Anywho, I have no idea how to easily store the struct inside the memory pool. This is my current code:

#include <stdlib.h>
#include <stdio.h>

#include "ex1.h"

#define POOL_SIZE 500


unsigned char mem_pool[POOL_SIZE];
unsigned char *ptr = &mem_pool[0];

typedef struct header Header;

Header h;

struct header{
    int size;
    char flag;
    Header * next;
};

void ma_init(){
    h = (Header){ .size = POOL_SIZE - sizeof(Header), .flag = 'F', .next = NULL};
}

Now ofcourse the h Header is not inside the mem_pool. Logically, int the initialisation it should be mem_pool[0] = (Header){ ..., since this is the first field of the mem_pool. Of course I could put pointers inside the array, but that would sort of ruin the aspec tof having a mem_pool.

So how should I store a struct (or whatever) in a certain location of the array?

1
  • maybe a linked list of allocation records either at the start of the pool or outside of it? Commented Mar 1, 2014 at 0:29

1 Answer 1

2

Your memory pool is just a blob of allocated memory and you are free to treat and interpret any portion of that memory in any way you want, you just need to be careful in your bookkeeping.

So you can declare that the first byte of your memory pool is the first byte of your header struct:

struct header *h = (struct header *)mem_pool;
h->flag = 'F';
// this will be set after you allocate the first block
// you would set it to h + sizeof(struct header) + allocation size
h->next = NULL;    

So as long as you have the start of your blob and your sizes/pointers are correct, you can just continue to cast the appropriate blob of memory as your struct.

Sign up to request clarification or add additional context in comments.

1 Comment

This only works if mem_pool is correctly aligned for struct header *, otherwise the behaviour is undefined. Since mem_pool is an array of a character type, it might not have the right alignment. One way to ensure mem_pool has the right alignment is to make it be a member of a union that also contains a pointer. Alternatively, if the pool is allocated with malloc that would also work because malloc'd memory is guaranteed to be aligned correctly for any type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.