我试图创建一个线程,在互斥锁的链表中插入数据,但只是得到分段错误。我必须设置许多线程与各种数据,只是在一个数据(如'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("%dn", 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("%dn", curr -> data);
curr = curr -> next;
free(curr);
}
return 0;
}
free()是动态分配所需要的,所以在main()函数中输入,但是终端说我得到分段错误。
我错在哪里?如何有效地识别问题?谢谢你的帮助。
如果head
是NULL
,那么head -> next
会给你一个分割错误。将head -> next = NULL (in main)
、head -> next == NULL (in list1)
分别替换为head = NULL
、head == NULL