Cristian
Cristian

Reputation: 303

pthread_mutex_init result in Segmentation Fault

I'm a college student learning how to deal with threads and databases. Overall, I'm trying to make a function that will take a list of locks, see if the current lock the program is handling is in the list, and mutex lock that lock. Currently, I am having issues initializing the *locks, but every time I do so, I get a segmentation error (core dump). I already try using the different ways of initializing the mutex lock: &locks->lock = PTHREAD_MUTEX_INITIALIZER; as well as using : pthread_mutex_init(&locks->lock, NULL);

on the .h file, it contains

typedef struct {
char *table;
pthrad_mutex_t lock;} TableLock;

main file:

static pthread_mutex_t lock_on_locks;
static int active_tables = 0;
static TableLock *locks = NULL;

// Table locking functions
void sudba_lock(char *table) {
  sleep(2);
  if (locks == NULL) {
    my_realloc(locks, sizeof(TableLock));
    }
  pthread_mutex_lock(&lock_on_locks);
  char table_name[strlen(table) + 1];
  table_name[strlen(table)] = '\0';
  sprintf(table_name, "%s", table);
  if (active_tables == 0) {
    pthread_mutex_init(&locks->lock, NULL);
    pthread_mutex_lock(&locks->lock);
    locks[active_tables].table = table_name;
    active_tables++;
  }

the my_realloc function is this:

void *my_realloc(void *ptr, size_t size) {
    void *result = malloc(size);
    if(!result) abort();
    return result
}

Any help is appreciated

Upvotes: 0

Views: 454

Answers (1)

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215259

Your crash has nothing to do with pthread_mutex_lock; it's just that you're passing a null pointer to it because you didn't save the result of realloc. Where you have:

my_realloc(locks, sizeof(TableLock));

it should be:

locks = my_realloc(locks, sizeof(TableLock));

But I'm not clear why you're allocating it anyway since this looks like a single-instance lock. Normally locks either have static storage duration or exist inside some structure you're allocating (whose contents they'll protect). Allocating an individual lock by itself is a code smell.

There are a lot of other things that look wrong with your code too, independent of the crash.

Upvotes: 1

Related Questions