首页 > 解决方案 > 互斥体创建创建分段错误

问题描述

我不明白为什么在创建以下互斥锁时会出现分段错误:

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#include <semaphore.h> // include POSIX semaphores
#include <fcntl.h>



struct semaphoreStruct{
  sem_t *mutex;
};




struct semaphoreStruct *semaphore_list;

int main(){

  sem_unlink("MUTEX");
  semaphore_list->mutex = sem_open("MUTEX", O_CREAT|O_EXCL,0700,1);
  return 0;
}

任何帮助将不胜感激!

标签: csegmentation-faultmutexsemaphore

解决方案


struct semaphoreStruct *semaphore_list由于没有为指针分配内存,因此出现分段错误。

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#include <semaphore.h> // include POSIX semaphores
#include <fcntl.h>

struct semaphoreStruct{
  sem_t *mutex;
};

struct semaphoreStruct *semaphore_list;

int main(){
  semaphore_list = malloc(sizeof(struct semaphoreStruct)); //allocate the memory for the struct
  sem_unlink("MUTEX");
  semaphore_list->mutex = sem_open("MUTEX", O_CREAT|O_EXCL,0700,1);
  return 0;
}

推荐阅读