Unexpected error in double linked list in C

末鹿安然 提交于 2020-01-04 04:26:12

问题


I am trying to insert elements in my double linked list based on the number of nodes n. Like if n is 4 then number of elements entered are: 34 45 32 1 but getting segmentation fault. Can anybody tell me where I am going wrong?

#include<stdio.h>
#include<malloc.h>

struct node{
            struct node *prev;
            struct node *next;
            int info;
            }*start;

create_list(int num)
{
 printf("Hi I entered!\n");
 struct node *q,*tmp;
 tmp= malloc(sizeof(struct node));
 tmp->info=num;
 tmp->next=NULL;

 if(start==NULL)
 {
  printf("Hi I am null!\n");
  tmp->prev=NULL;
  start->prev=tmp;
  start=tmp;
 }

 else
 {
  printf("Hi I am no more null!\n");
  q=start;
  while(q->next!=NULL)
  q=q->next;
  q->next=tmp;
  tmp->prev=q;
  }
}




int main(){

int choice, n, elem,i;
start = NULL;

 printf("Enter your choice of number: \n");
 scanf("%d", &choice);

 while(1)
      {

switch(choice)
{
  case 1:
     printf("Enter the number of nodes: \n");
     scanf("%d", &n);

     for(i=0; i<n; i++)
     {
       printf("Enter the elemnts: \n");
       scanf("%d", &elem);
       create_list(elem);
     }
     break;

 default:
         printf("You have tyoed wrong!\n");
     }

   }
 }

回答1:


if(start==NULL)
{
  ...
  start->prev=tmp;

If start is NULL, then the assignment above is incorrect.

I would suggest initializing prev to NULL when you allocate the new node like this:

tmp= malloc(sizeof(struct node));
tmp->info=num;
tmp->next=NULL;
tmp->prev=NULL;        // add this

if(start==NULL)
{
    printf("Hi I am null!\n");
    start=tmp;
}
....



回答2:


You are trying to dereference a NULL pointer here:

if(start==NULL)
{
    printf("Hi I am null!\n");
    tmp->prev=NULL;
    start->prev=tmp;    //start is NULL

Since pointer to struct start does not point to any memory, you can't use it to asing data.




回答3:


You have an infinite while loop. Set some variable after you have finished inserting into the list. check this variable after coming out of the switch case and break again from the while loop.



来源:https://stackoverflow.com/questions/18763139/unexpected-error-in-double-linked-list-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!