Pergunta

I am trying to create a simple C program while learning about the concepts about pointers, linked list and header files. I want to create a simple C program by clubbing all these concepts together for better understanding. My code and its explanation is as follows:

I have a header file "header1.h " where I have declared the structure which is to be shared between various source files and also the "head" variable of the linked list. The header file is as follows:

header1.h

 struct node{

        char * name;
        struct node* next;
 };

 extern struct node* head;

Now, I have the main source-file named "start_prog.c" which has got the "main" function and the menu which will control the execution of the of the program. Menu has various options such as Add element ,Delete element , Reverse List etc (for simplicity I will only present two options here viz, Insert and Print list which are most important).

from the start_prog.c I call the "create" function which will add the element to the list. If the list does not exist then it will create one else It will append the element to the list after the last element. The create function is defined in another source file "create.c".

Both the files are as follows:

start_prog.c:

#include<stdio.h>
#include<stdlib.h>
#include "header1.h"    //include the header file

struct node* head = NULL;   //Define the external variable head to be null initially

struct node* create();
void main(void){


    int option;

    do{

       printf("\nplease select the option : \n\t\t1)add element \n\t\t2)Print List\n");

    scanf("\n%d",&option);

    switch(option){
    case 1:
            head = create();
            break;
    case 2:
            print_list();
            break;

    }

    }while(option != 3);

}

and the create.c file is as follows:

#include<stdio.h>
#include<stdlib.h>                                                                                                              
#include "header1.h"
 //this function creates the linked list if the list is null or inserts the
 //element at the end of the list.


struct node* create() {

    if(head == NULL){

  //create a new list and return head.
      printf("\nhead is null\n");
      struct node* newnode = (struct node*)malloc(sizeof(struct node));
      char * new_name;
      printf("\nplease enter the new name\n  ");
      scanf("%s\n", new_name);
      newnode -> name = new_name;
      newnode -> next = NULL;
      head = newnode;
      return head; 



    }

    else if(head != NULL){

      printf("\nhead is not null\n ");
      struct node* newnode = (struct node*)malloc(sizeof(struct node));
      char * new_name;
      printf("\n Please Enter the new name \n");
      scanf("%s\n", new_name);
      newnode -> name = new_name;
      newnode -> next = NULL;

      struct node* ptr = NULL;

      ptr = head;
      while((ptr -> next) != NULL){

            ptr = ptr -> next;


      } 

            ptr -> next = newnode;
            return head;

    }



}

when I run all these programs together I get Garbage values in the head and Segmentation fault error. What is Wrong in my code. What is the thing that I am missing. I feel that I am close to understand the concepts but missing some important point due to which I am not able to write the program properly. Please find the bug/error in my code and the fault in my understanding. Thankyou!

Foi útil?

Solução

Generally Segmentation fault occurs when you to try to access or assign value from/to memory which is not assigned to that process.

Normally check places where you are assigning values or retrieving it whether your the is assigned to it or not.

one think i saw was

char * new_name; // declaring the pointer
printf("\n Please Enter the new name \n");
scanf("%s\n", new_name);//reading the value from stdin to where pointer is pointing

when you declare the pointer its filled with garbage value. which may be out of range of your process assigned memory. and your asking your compiler to store the value there which is illegal hence the kernel raises a signal SIGSEGV and halts your process.

Assign memory before assigning the value

new_name = malloc(20); // how much ever you think is required

Outras dicas

In your create.c file

char * new_name; printf("\nplease enter the new name\n "); scanf("%s\n", new_name);

How will that above code execute, Please try to use array to store name temporarily there. if you want to use pointer there then you have to allocate memrory for that poiner too. and dont use '\n' in the scanf like that or else, it will not stop even when you press enter key it will stop only when you press any non-white space charater,which would be awfull.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top