-1

I am new to C programming and When I asked user to input a number for some reason my whole program gives this error

Program received signal SIGSEGV, Segmentation fault.
0x0000555555555753 in addData (word=0x7fffffffeb70 "", mode=2) at main.c:202
202                 if (temp->next == NULL) {
(gdb) 

HERE IS MY CODE


#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#define MEMORY 6
#define MAX_word_LENGTH 11 
int numberOfwords;
char words[MEMORY][MAX_word_LENGTH];
struct Node{
    int data;

    char *word;

    struct Node *next, *prev;
};

struct Node *head, *tail;
struct Node* DlListDeleteLastNode(struct Node *head);
void addData(char *word, int mode);
void DisplayForward();
struct Node* deletePos(struct Node *head, int pos);
int getPostion(char *targetWord);
bool search(char *targetWord);
//struct Node* deletePos(struct Node *head, int pos);
int countWord(char *wording);
void insert_specified(char *wording, int pos);
int countNodes();

//void init(){
//   head = NULL;
//   tail = NULL;
//}
int main()
{
    
    
   char name[100];
   //char searchName[] = "barr";
   printf("Enter number of words to be stored in the word stream: ");
   
    int input;
    scanf("%d", &input);
    
   
   int i;
   int count = 0; 
   for (i=0; i<input;i++){
      count++;
      printf("\nEnter name %d : ",count);

      scanf ("%[^\n]%*c", name);
      //scanf("%s[^\n]",words[i]);
      addData(name, 2);
   }
   
   
   //for (int i = 0; i <4; i++) {
   //    strcpy(words[i], 
   //}
  //insert_specified(searchName, 0);
  //printf("%d\n", numberOfwords);
  //DlListDeleteLastNode();
  DisplayForward();
  //int num = countNodes();
  //printf("count %d", num);
  //deletePos(head, 3);
  //bool x = search(searchName);
  //printf("%d\n", x);
  //printf("%d\n", numberOfwords);
  //DisplayForward();
  //fflush(stdin);
  printf("\nEntered names are:\n");
     for(i=0;i<6;i++)
     puts(words[i]);
}
int isEmpty(struct Node *h){
    if(h==NULL)
        return 1;
    else
        return 0;
}

void addData(char *word, int mode){

if (mode == 1) {
    for (int i=0; i<5; i++) {
        if (strcmp(words[i],word) == 0) {
            //printf("found\n");
            //printf("FOUND%s\n", word);
            int x = getPostion(word);
            //printf("index found %d/n", x);
            //deletePos(head, x);
            struct Node* temp = head;
            struct Node* temp2 = NULL;
            while (x > 1) {
                temp = temp->next;
                x--;
            }
            if (temp->next == NULL) {
                head = DlListDeleteLastNode(head);
            }
            else {
                temp2 = temp->prev;
                temp2->next = temp->next;
                temp->next->prev = temp2;
                free(temp);
                temp = NULL;
                
            }
            break;
        }
        
        //x index = getPostion()
        
    }
    if (numberOfwords >= 5) {
        DlListDeleteLastNode(head);
        struct Node *ptr;   
       ptr= malloc(sizeof *ptr);
       ptr->word = malloc(sizeof(char) * 12);
        //char nimI[20];
        
        //baru->nim = malloc(12 * sizeof(char));
       //strcpy(ptr->word, word);
     
       if(head==NULL)  
       {  
           ptr->next = NULL;  
           ptr->prev=NULL; 
           strcpy(ptr->word, word);
           //ptr->word= word;  
           head=ptr;  
           //head = ptr;
           //tail = ptr;
       }  
       else   
       {  
           //ptr->word=word;  
           strcpy(ptr->word, word);
           ptr->prev=NULL;  
           ptr->next = head;  
           head->prev=ptr;  
           head=ptr;  
       }
       numberOfwords++;
    }
    else {
        struct Node *ptr;   
       ptr= malloc(sizeof *ptr);
       ptr->word = malloc(sizeof(char) * 12);
        //char nimI[20];
        
        //baru->nim = malloc(12 * sizeof(char));
       //strcpy(ptr->word, word);
     
       if(head==NULL)  
       {  
           ptr->next = NULL;  
           ptr->prev=NULL; 
           strcpy(ptr->word, word);
           //ptr->word= word;  
           head=ptr;  
           //head = ptr;
           //tail = ptr;
       }  
       else   
       {  
           //ptr->word=word;  
           strcpy(ptr->word, word);
           ptr->prev=NULL;  
           ptr->next = head;  
           head->prev=ptr;  
           head=ptr;  
       }  
       numberOfwords++;
       strcpy(words[numberOfwords], word);
        
    }
        
    
       
        
}
else {
    int flag = 0;
    //int numWords = countNodes();
    for (int i=0; i<8; i++) {
        if (strcmp(words[i],word) == 0) {
            //printf("found\n");
            //printf("FOUND%s\n", word);
            int x = getPostion(word);
            //printf("index found %d/n", x);
            //deletePos(head, x); //
            struct Node* temp = head;
            struct Node* temp2 = NULL;
            while (x > 1) {
                temp = temp->next;
                x--;
            }
            if (temp->next == NULL) {
                head = DlListDeleteLastNode(head);
            }
            else {
                temp2 = temp->prev;
                temp2->next = temp->next;
                temp->next->prev = temp2;
                free(temp);
                temp = NULL;
                
            }
            
            flag = 1;
            
            //DisplayForward();
            //numberOfwords--;
            break;
        }
        
        //x index = getPostion()
        
    }
    printf("\nflag num-> %d\n", flag);
    //numberOfwords++;
    int numWords = countNodes();
    if (numWords >= 5 && flag==0) {
       //printf("activated");
       int max = 0;
       char maxWord[50];
       for (int i = 0; i < 8; i++) {
           int num = countWord(words[i]);
           if (num > max) {
               max = num;
               //printf("%d", max);
               strcpy(maxWord, words[i]);
               //printf("word %s\n", maxWord);
           }
           
           
       }
       printf("most occured word: %s\n", maxWord);
       int mostOccuredWordIndex = getPostion(maxWord);
       printf("index: %d\n", mostOccuredWordIndex);
       mostOccuredWordIndex--;
       insert_specified(word, mostOccuredWordIndex);
       DlListDeleteLastNode(head);
       
        
        
    }
    
    else if (numWords >= 5) {
        //DlListDeleteLastNode(head);
        //struct Node *ptr;   
       //ptr= malloc(sizeof *ptr);
       //ptr->word = malloc(sizeof(char) * 12);
        //char nimI[20];
        
        //baru->nim = malloc(12 * sizeof(char));
       //strcpy(ptr->word, word);
       
       //Get most occured word in words array
       
       //find the position of the most occured word
       //int mostOccuredWordIndex = getPostion(maxWord);
       //remove last element and insert new word into that position
       
       //if position is in the last index then remove word and replace with the word 
       //if (mostOccuredWordIndex == 5) {
        //   printf("occurred");
           
       //}
       // 
       DlListDeleteLastNode(head);
       numberOfwords = numberOfwords + 1;
       struct Node *ptr;   
       ptr= malloc(sizeof *ptr);
       ptr->word = malloc(sizeof(char) * 12);
       if(head==NULL)  
       {  
           ptr->next = NULL;  
           ptr->prev=NULL; 
           strcpy(ptr->word, word);
           //ptr->word= word;  
           head=ptr;  
           //head = ptr;
           //tail = ptr;
       }  
       else   
       {  
           //ptr->word=word;  
           strcpy(ptr->word, word);
           ptr->prev=NULL;  
           ptr->next = head;  
           head->prev=ptr;  
           head=ptr;  
       }
       
    }
    
    
    
    else {
        struct Node *ptr;   
       ptr= malloc(sizeof *ptr);
       ptr->word = malloc(sizeof(char) * 12);
        //char nimI[20];
        
        //baru->nim = malloc(12 * sizeof(char));
       //strcpy(ptr->word, word);
     
       if(head==NULL)  
       {  
           ptr->next = NULL;  
           ptr->prev=NULL; 
           strcpy(ptr->word, word);
           //ptr->word= word;  
           head=ptr;  
           //head = ptr;
           //tail = ptr;
       }  
       else   
       {  
           //ptr->word=word;  
           strcpy(ptr->word, word);
           ptr->prev=NULL;  
           ptr->next = head;  
           head->prev=ptr;  
           head=ptr;  
       }  
       numberOfwords = numberOfwords + 1;
       strcpy(words[numberOfwords], word);
        
    }
    DisplayForward();
    numWords = countNodes();
    printf("\nnumber of words%d \n", numWords);
}
}
    




struct Node* DlListDeleteLastNode(struct Node *head) {
    struct Node *temp = head;
    struct Node* temp2; 
    while (temp->next != NULL) {
        temp = temp->next;
    }
    temp2 = temp->prev;
    temp2->next = NULL;
    free(temp);
    numberOfwords--;
    return head;
}
void DisplayForward() {  
    //Node current will point to head  
    struct Node *current = head;  
    if(head == NULL) {  
        printf("List is empty\n");  
        return;  
    }  
    printf("["); 
    int count = numberOfwords; 
    // while current->next != Null
    while(current!=NULL) {  
        //Prints each node by incrementing pointer.  
        printf("%s, ", current->word);  
        current = current->next;  
        count--;
    }  
    //current = current->next;  
    //printf("%s]\n", current->word);  
    //printf("%d", numberOfwords);
}  

bool search(char *targetWord) {
   int pos = 0;
   
   if(head==NULL) {
      printf("Linked List not initialized");
      return;
   } 

   struct Node *current = head;
   //current = head;
   
   while(current!=NULL) {
      pos++;
      if(strcmp(current->word, targetWord) == 0) {
         printf("%s found at position %d\n", targetWord, pos);
         return true;
      }

      if(current->next != NULL)
         current = current->next;
      else
         break;
      
   }
   return false;
   //printf("%s does not exist in the list\n", targetWord);
}
int getPostion(char *targetWord) {
    int pos = 0;
   
   if(head==NULL) {
      printf("Linked List not initialized");
      return -1;
   } 

   struct Node *current = head;
   //current = head;
   while(current!=NULL) {
      pos++;
      if(strcmp(current->word, targetWord) == 0) {
         //printf("%s found at position %d\n", targetWord, pos);
         return pos;
      }

      if(current->next != NULL)
         current = current->next;
      else
         break;
      
   }
   return -1;
   //printf("%s does not exist in the list\n", targetWord);
}


int countWord(char *wording) {
    int count = 0;
    for(int i=0;i<6;i++) {
        if (strcmp(words[i], wording)==0) {
            //printf("found word");
            count++;
        }
    }
    return count;
}

void insert_specified(char * wording, int pos)  
{  
   struct Node *ptr;
   ptr= malloc(sizeof *ptr);
   ptr->word = malloc(sizeof(char) * 12);
   struct Node *temp;   
   int i;   
   if(ptr == NULL)  
   {  
       printf("\n OVERFLOW");  
   }  
   else  
   {  
       //printf("\nEnter the location\n");  
       //scanf("%d",&loc);  
       temp=head;  
       for(i=0;i<pos;i++)  
       {  
           temp = temp->next;  
           if(temp == NULL)  
           {  
               printf("\ncan't insert\n");  
               return;  
           }  
       }  
       strcpy(ptr->word, wording); 
       ptr->next = temp->next;  
       ptr -> prev = temp;  
       temp->next = ptr;  
       temp->next->prev=ptr;  
       printf("Node Inserted\n");  
   }  
}
int countNodes() {  
    int counter = 0;  
    //Node current will point to head  
    struct Node *current = head;  
      
    while(current != NULL) {  
        //Increment the counter by 1 for each node  
        counter++;  
        current = current->next;  
    }  
    return counter;  
} 

I tried to ask the user for a number of words it wants to input for my program to store the items in a doubly linked list but instead gives a segmentation fault error

jxh
  • 69,070
  • 8
  • 110
  • 193
  • Run your code through valgrind. If you're mismanaging memory it will tell you where – dbush Dec 08 '22 at 00:04
  • quick compile - search does not return a value if head==null – pm100 Dec 08 '22 at 00:10
  • when i run it temp2 is null inside DlListDeleteLastNode – pm100 Dec 08 '22 at 00:13
  • see also https://stackoverflow.com/questions/5240789/scanf-leaves-the-newline-character-in-the-buffer – pm100 Dec 08 '22 at 00:14
  • https://tio.run/##jVBBboMwELz7FaP0YhJShRyqSAROPfcDEQfLdoIlMBE4DRLi7XSNUwl66h7s0e7M2Dtyf5Nymt6MldVDaZw71xp7ey9zxmQpWjybVnWXj@KSJEXKaPqQDl@N0gMD1aKBrdW9S9mYMrZql1oo6n03RkEo9Smc4LP31pvHMNahJmZEpBkLY3nEwgO/gs0mxpEY43@MBmau4B4iy5BEGEinq04jmF6bFtyzTXZIYc4nOna76DX15fW0hKzvPCRgitiDyBselsyZTVY9MhzTVXuVgtP1nSghjCXrWZpKg/fIw0/xp15Cf@3zEPFyPLI1GmnVcZp@AA – jxh Dec 08 '22 at 00:46
  • You really should do a little more work than just posting a stack trace i.e. [mre]. Like minimize your code, remove comment out code etc. MEMORY is defined as 6 but you hard-code 8 in your loop conditions. – Allan Wind Dec 08 '22 at 05:21
  • That giant if statement in addDate() is a hint that you may want to two different functions (one for each mode). – Allan Wind Dec 08 '22 at 05:41
  • Please trim your code to make it easier to find your problem. Follow these guidelines to create a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – Community Dec 08 '22 at 11:35

1 Answers1

0

struct Node *head is a global variable which is zero initialized. In addData() you set struct Node* temp = head; and then you deference temp like your stack trace shows which will segfault.

Anyways, before you even get there the 2nd scanf() fails as it the input buffer contains the \n from reading the previous number. The syntax of the format string also looks wrong to me. In any case as you don't check the return value of you are operating on uninitialized data. Here is the minimal fix:

        if(scanf(" %99[^\n]*", name) != 1) {
            printf("scanf failed\n");
            return 1;
        }

I also replaced the hard-coded < 8 with < MEMORY to avoid a buffer overflow. Here is an example run:

Enter number of words to be stored in the word stream: 2

Enter name 1 : test

flag num-> 0
[test, 
number of words1 

Enter name 2 : test2

flag num-> 0
[test2, test, 
number of words2 
[test2, test, 
Entered names are:

test
test2



Allan Wind
  • 23,068
  • 5
  • 28
  • 38