I want to implement malloc in a multithreaded environment, and I got the code from here.
After adding in mutex:
typedef struct free_block {
size_t size;
struct free_block* next;
pthread_mutex_t lock;
} free_block;
void free_block_init(free_block *FB){
pthread_mutex_init(&FB->lock, NULL);
}
static free_block free_block_list_head = { 0, 0 };
static const size_t overhead = sizeof(size_t);
static const size_t align_to = 8;
void* mymalloc(unsigned int size) {
size = (size + sizeof(size_t) + (align_to - 1)) & ~ (align_to - 1);
free_block* block = free_block_list_head.next;
pthread_mutex_lock(&block->lock);
free_block** head = &(free_block_list_head.next);
while (block != 0) {
if (block->size >= size) {
*head = block->next;
pthread_mutex_unlock(&block->lock);
return ((char*)block) + sizeof(size_t);
}
head = &(block->next);
block = block->next;
}
block = (free_block*)sbrk(size);
block->size = size;
pthread_mutex_unlock(&block->lock);
return ((char*)block) + sizeof(size_t);
}
unsigned int myfree(void* ptr) {
free_block* block = (free_block*)(((char*)ptr) - sizeof(size_t));
pthread_mutex_lock(&block->lock);
block->next = free_block_list_head.next;
free_block_list_head.next = block;
pthread_mutex_unlock(&block->lock);
}
I'm only able to allocated memory to the first block, then a segmentation fault error. I don't know where my error is and I'm very new to threads and locks, so any sort of help would be great! Thanks.