Jump to content
xisto Community
Sign in to follow this  
kvarnerexpress

Programming A Malloc

Recommended Posts

A little background about what I am doing is this:
I have an array which holds a linked list containing the memory that is currently taken from the system.

Each index I have like 16 size memory or less can be stored only in index 0, index 1 is for memory inbetween 16-32, index 2 is for memory inbetween 32-64, etc all the way up to 2048 which is the max allocatable memory.

Now the way my malloc is to work is that it first will run through my list to see if any memory is available that is greater than or equal to the size I need, if there is any at all it will return it.

Then if the memory is too big it will split it in half and stick it into the freelist and repeat till the memory is the right size.

Almost everything is working great except when I split my memory. My split memory function works fine if you split only once in a call to the malloc, if you split more than once it crashes.

Im confused as to why though.

Here is the function:


Code:

metadata_t* split_memory(metadata_t* memory){  printf("Splitting the memory has been called \n");  printf("Old Memory Size is: %d\n",memory->size);  printf("%p\n",memory);  metadata_t* second = memory + (memory->size / 2);  printf("%p\n",second-memory - memory->size/2);  size_t temp = memory->size / 2;  memory->size = temp;  second->size = temp;  printf("Unaccounted for space: %d\n",memory->size + second->size - temp * 2);  printf("New Memory Size is: %d\n",second->size);    memory->next = second;  second->prev = memory;      return memory;}

Share this post


Link to post
Share on other sites

I think in your code second->next is unassigned and is hanging. When you try to use it, it crashes. So,

before your

memory->next = second;

you need to add

second->next = memory->next;

making second->next point to next memory originally pointed by "memory".

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.