-1

I'm new to C language and having this problem alot, the code compiles with no problems yet still get this message:

Segmentation fault
when trying to execute my code on UNIX terminal. This is the code:
///MAIN FUNCTION///
int main() {
        printf("==========================J.U.S.T=======================$
        printf("Enter your option number:\n1- working with an existing f$
        char choice[1];
        scanf("%c",choice);
        if(choice[0] == '1'){
                printf("first choice");
        }
        else if(choice[0] =='2' ){
                printf("Enter the following data one by one:");
                char BookT[50],AUTHORn[50];long int ISBN;
                printf("Book Title:");
                scanf("%s",BookT);
        //      sleep(5);
                printf("Author name:");
                scanf("%s",AUTHORn);
        //      sleep(5);
                printf("Book number:");
                scanf("%d",ISBN);
        //      sleep(5);
                printf("%s\n%s\n%d\n",BookT,AUTHORn,ISBN);
        }
        else printf("Wrong choice try again!!");
        return 0;
}

I'm using Kali linux to compile the code.

Paul Floyd
  • 5,530
  • 5
  • 29
  • 43
Somaiah Mohd
  • 1
  • 1
  • 4
  • Is it always causing the segfault or only when you input certain values? – Blaze Oct 03 '18 at 12:37
  • 1
    In first and second `printf` you are missing terminating `"` character, How will it compile? – Mayur Oct 03 '18 at 12:39
  • Please fix your code snippet and use the correct method to insert code snippets using markdown syntax. As is, your code had too many unrelated problems to wire up a proper answer – Lie Ryan Oct 03 '18 at 12:44

3 Answers3

2

As you probably have noticed, the segmentation fault happens at the line scanf("%d",ISBN);

scanf requires a pointer to save the result in, but you are passing it the value of the variable ISBN. In order to save the result in the ISBN variable you should send it a pointer to the variable instead: scanf("%d", &ISBN);

(arrays already work (more or less) the same way as pointers, so there is no need to use & when reading strings)

David Narum
  • 312
  • 2
  • 3
1

You should add an ampersand and proper format specifier to scanf
scanf("%ld",&ISBN);

Mayur
  • 2,583
  • 16
  • 28
1

Just change the line scanf("%d", ISBN); by scanf("%d", &ISBN); , scan requires a pointer and you are trying to save the result without pointer, so the program will just segfault. But if you give him the adress of the variable, he can reach it and save the result in it.

Zahreddine Laidi
  • 560
  • 1
  • 7
  • 20