I'm trying to create my own version of malloc using best fit. To do this I am using linked lists to keep track of the allocations. However when I go to allocate space, the linked lists dont seem to be connecting. I've gone through the code over and over but can't see the problem. Any help would be appreciated so much.
1 Answer
One problem is in allocating your node structures:
root = (struct node *)sbrk(sizeof(root));
...
added = (struct node *)sbrk(sizeof(root));
Should be:
root = (struct node *)sbrk(sizeof(*root));
...
added = (struct node *)sbrk(sizeof(*root));
At best, your nodes and your allocations would "share" memory incorrectly.
Also, I think you need to be careful to ensure proper alignment of your memory. I'm not sure your code (or sbrk) does that.
Here's a problem with your splitting code:
return best+sizeof(best);
...
newnode = best+best->mallocsize+sizeof(root);
Since best is a struct node*, these additions jump further ahead in memory than I think you intended. I think you meant to cast best to a (char*) in these expressions.
Also, I think the computation for newnode is wrong, even after you cast to (char*). I think you want something more like:
newnode = best + 1 + size / sizeof(*root) + !!(size % sizeof(*root));
You also forget to compute and set newnode->mallocsize!
The following math probably will be done in unsigned (i.e. - int's promoted to size_t's):
if (best->mallocsize-size-sizeof(short) < sizeof(root)) {
In that case, you can underflow 0 on the left hand side, which will cause you to improperly split the node. You can fix this by throwing the subtraction over to the other side of the inequality because you already ensured that size < best->mallocsize:
if (best->mallocsize - size < sizeof(root) + sizeof(short)) {
Couple of other points:
- In your best fit search, you almost always skip over the root for some reason.
- In your best fit search, you don't consider unused node's whose
mallocsizeequalssize. - In your best fit search, once you find an optimally sized unused node (i.e. -
size == current->mallocsize), end the search (i.e. - break the loop). - In your allocations you call
sbrktwice: once for your node and once for the application's memory. If you are doing this to ensure proper alignment of memory, then that's good (assumingsbrkdoes this for you), but then your assumption that anode + 1gives you the address of the application's memory may not be true.
#include "mymalloc.h". So the struct/list definition is available.my_free()look like? I assume that is the function that puts memory areas onto the free list?