i am writing a simple function for a library, that will take in as a parameter the size of memory to be managed by my other functions.
i have a data structure that holds the information of this large memory pool initialized by the user.
typedef struct memBlock{
struct memBlock* next;
unsigned int size; // Size of this block
unsigned int is_used; // bool 0 = not used 1 = used
} memBlock;
I also have this function that i am trying to figure out how to initialize this data structure as well as allocate enough space to be managed initially?
int initialize_memory(unsigned long size){
memBlock *ptr; // the beginning of our whole memory to be handled
ptr = malloc(size); // this is the ptr to the original memory first allocated.
ptr->next = NULL;
ptr->size = NULL;
ptr->is_used = 0;
has_initialized = 1; // the memory has been initialized
}
please help
Change
ptr->size = NULL;toptr->size = size;. You also need to returnptr, or store it somewhere. Your function returnsint, but you don’t return anything.has_initializedseems unnecessary — you know you’ve initialized because your memory pool (theptrvalue you will return) isn’tNULL. If you need more help than that, you’re going to have to explain more.Addendum: You need to decide whether memBlock.size is the size of the allocated space or the size of the memory block represented by the memBlock … if the latter, then you need to account for the space occupied by the memblock itself by subtracting that off the amount of space you allocated:
ptr->size = size - sizeof(struct memBlock);You also need a way to address your memory pool … since that immediately follows the memBlock, its address is(ptr + 1)or&ptr[1](if you don’t understand that, look up “pointer arithmetic in C”).P.S. You wrote in a comment “Essentially i also have another function that will act like ‘malloc’ to reserve a number of bytes but will first check this data structure to see if any memory is available from my pool”
Why do you want to do that? malloc already manages memory far better than your function will, considering the skill level and time invested, and there’s no point in layering another memory allocator on top of it. Unless this is a school project to write a memory allocator, in which case you should say that up front.