【问题标题】:Segmentation fault in linked list with mutex具有互斥锁的链表中的分段错误
【发布时间】:2022-11-28 13:57:46
【问题描述】:

我正在尝试创建线程,该线程使用互斥锁将数据插入链表中,但只是出现分段错误。我必须用各种数据设置许多线程,并且只是在用一个数据(如“10”)和一个线程进行实验的过程中。

typedef struct NODE{
    int data;
    struct NODE* next;
    pthread_mutex_t lock;
}node;

node* head;

void* list1(void* args){
    node *prev, *new_node;
    pthread_mutex_lock(&new_node->lock);
    new_node = (node*) malloc(sizeof(node*));
    new_node -> data = 10;
    new_node -> next = NULL;
    if(head -> next == NULL){
        head = new_node;
    }else{
        prev = head;
        pthread_mutex_lock(&prev->lock);
        while(prev -> next != NULL){
            prev = prev -> next;
        }
        prev -> next = new_node;
        pthread_mutex_unlock(&prev->lock);
        pthread_mutex_unlock(&new_node->lock);
    }
    pthread_mutex_destroy(&prev -> lock);
    pthread_mutex_destroy(&new_node -> lock);
}

int main(void){
    void *thread_result;
    int status, cnt;
    pthread_t thread_id[1];
    head -> next = NULL;
    printf("%d\n", 1);

    status = pthread_create(&thread_id[0], NULL, list1, NULL);
    pthread_join(thread_id[0], &thread_result);
    node* curr = head -> next;
    while(curr -> next != NULL){
        printf("%d\n", curr -> data);
        curr = curr -> next;
        free(curr);
    }
    return 0;
}

free() 是动态分配所必需的,因此在 main() 函数中输入,但终端说我遇到了分段错误。

我的错误是什么?以及如何有效地识别问题?我很感激你的帮助。

【问题讨论】:

    标签: c linked-list segmentation-fault dynamic-memory-allocation


    【解决方案1】:

    如果 headNULL 那么 head -> next 会给你一个分段错误。 将head -> next = NULL (in main)head -> next == NULL (in list1)分别替换为head = NULLhead == NULL

    【讨论】:

      猜你喜欢
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-10
      • 2012-06-05
      • 2015-10-06
      相关资源
      最近更新 更多