【发布时间】: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