I try to implement a custom malloc function. I have issues with the size part. Since we can free a variable, the empty space can be reallocated. The custom structure is 32 bits long and contains the size of the data and a bit as a boolean (unsigned int free : 1) that says if the data is free or not.
Here is my malloc function :
void *mymalloc(size_t size) {
if (!size) return NULL;
size_t length = align(size + sizeof(struct header));
Header current = availableHeader(size);
if (!(current==sbrk(0))) {
Header newHeader = sbrk(length);
if (newHeader == (void*) -1) {
return NULL;
}
newHeader->size = length - sizeof(struct header);
current = newHeader;
} else if (length + sizeof(size_t) < current->size) {
split(current, length);
}
current->free = 0;
return current+sizeof(struct header);
}
This uses a function called "availableHeader" that will find the first available memory morsel, a new one if no other morsel is free AND has enough size to store the data.
Header availableHeader(size_t s) {
Header current = firstHeader();
int isHeader=1;
for (;isHeader && (!current->free || current->size < s); current = current+current->size+sizeof(struct header)){
printf("%d on %d for %d\n", current->free, current->size, s);//TEST
if(current>=sbrk(0)){
isHeader=0;
}
}
return current;
}
And finally, this function uses "firstHeader" which returns the first morsel we created, it creates the first one if it's the first call.
static void *firstHeader() {
static Header b = NULL;
if (!b) {
b = sbrk(align(sizeof(struct header)));
if (b == (void*) -1) {
_exit(127);
}
b->size = 0;
b->free = 0;
}
return b;
}
Now, the problem is that "availableHeader" never returns an already-created block. It always results in creating a new one which is a terrible memory management strategy. By testing (marked //TEST) i saw that my loop in "availableHeader" always sees the current memory block with "0" for both size and free.
It seems like my malloc function never sets a size even though there is this line :
newHeader->size = length - sizeof(struct header);
But the issue stays : reading the size in "availableHeader" returns 0 even if it has another value.
EDIT : As requested, here's the structure :
struct header {
unsigned int size : 29,
zero : 2,
free : 1;
};
static Header b = NULL;-->>static Header *b = NULL;maybe?current+sizeof(struct header);wrong pointer arithmetic.