This is a stripped-down version of some code that works perfectly fine as a single-threaded program. I am trying to make it multithreaded. The goal is to have a global list of structs, and, in a loop, reallocate memory for the list and extend its size by one struct for each iteration of the loop. I receive the following error:
Terminated due to signal: ABORT TRAP (6)
doublefree(54652,0x70000020a000) malloc: *** error for object
0x7fbc13403400: double free
As mentioned, it works if the number of threads is one. I'm assuming the multiple threads are attempted to free the same memory during realloc(). But shouldn't the mutex prevent that? The pointer for the list is global, so shouldn't every thread see the changed pointer made by the others? I don't see how this is any different from the single-threaded version. If I run it over and over again, I can eventually get the correct output, so there is some race condition that I'm not seeing.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
typedef struct {
char key[512];
int value;
} KV_Pair;
KV_Pair *pairList;
int count = 0;
void *doStuff(void *args);
pthread_mutex_t mutex;
int main(int argc, char *argv[]) {
pairList = malloc(sizeof(KV_Pair));
pthread_t threads[4];
int i;
for(i = 0; i < 4; i++) {
pthread_create(&(threads[i]), NULL, doStuff, NULL); }
for(i = 0; i < 4; i++) {
pthread_join(threads[i], NULL); }
free(pairList);
}
void *doStuff(void *args) {
while (1) {
pthread_mutex_lock(&mutex);
count++;
pairList =
realloc(pairList, sizeof(KV_Pair) * count);
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}