Thread: IF statement creates a segmentation fault.

  1. #1
    Registered User
    Join Date
    Dec 2015
    Posts
    2

    IF statement creates a segmentation fault.

    Hi everyone,

    Completely new to C and working on my own. I am using Code blocks. Why does this create a segmentation fault?

    Code:
    #include <stdio.h>
    
    
    int main()
    {
        int x ;
    
        printf("Type in the key\n");
         scanf("%d, &x");
    
        if ( x == 10 )
        {
           printf("Entered key number was correct!"); /* execute this line if above IF condition is TRUE*/
        }
    
        else
        {
            printf("Entered key number was incorrect"); /* execute this line if above IF condition is FALSE*/
        }
        return 0;
    }

  2. #2
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    You should make sure you are compiling with maximum warnings enabled.

    Code:
    /*
    main.c||In function 'main':|
    main.c|9|warning: too few arguments for format|
    main.c|11|warning: 'x' is used uninitialized in this function|
    ||=== Build finished: 0 errors, 2 warnings ===|
    */
    These indicate you have a problem with your "scanf()" call. Looking closely, you have the closing quote in the wrong place.

    It should be:

    Code:
    scanf("%d", &x);

  3. #3
    Registered User
    Join Date
    Dec 2015
    Posts
    2
    Thank you so much!

    Have put the extra warnings on now

    Cheers

  4. #4
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    Very nice! You're welcome!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. In GDB no segmentation fault but while running segmentation fault
    By Tamim Ad Dari in forum C++ Programming
    Replies: 2
    Last Post: 12-10-2013, 11:16 AM
  2. Segmentation Fault?
    By ronaldh12 in forum C Programming
    Replies: 4
    Last Post: 02-11-2012, 03:28 PM
  3. Segmentation Fault hmm?
    By pobri19 in forum C Programming
    Replies: 4
    Last Post: 05-03-2008, 07:51 AM
  4. Replies: 12
    Last Post: 03-05-2008, 09:51 AM
  5. segmentation fault and memory fault
    By Unregistered in forum C Programming
    Replies: 12
    Last Post: 04-02-2002, 11:09 PM

Tags for this Thread