Reputation: 203
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.
Upvotes: 2
Views: 760
Reputation: 8514
In this line:
pthread_mutex_lock(&block->lock);
you haven't checked yet whether block
is NULL. You would need to do the locking inside the loop.
Easier still, why not have just one mutex for your whole malloc - make it a static next to free_block_list_head
then you can just lock it at the start of your function and unlock it after.
If you do stick with a per block mutex, remember to add space for the mutex to your calculations. You also need to make sure the pointer you pass back is pointing to memeory after your mutex in the data structure.
Edit: Also note: You also haven't called free_block_init
anywhere.
Upvotes: 2