Home > Software design >  c: segfault when using scanf with a character
c: segfault when using scanf with a character

Time:06-13

I am writing a simple program that takes in user input (a char) and does a simple calculation. However, it segfaults before even hitting scanf.

The other posts I've looked at (below) fix the problem by adding more memory to the char buffer, or passing the address of the variable instead of the variable itself, etc., but that doesn't fix the problem.

Why is this happening and how do I fix it? other posts I've looked at: Segfault when using scanf()

C Programming segfault on scanf

SegFault after scanf?

#include <stdio.h>
int main(int argc, const char * argv[]) {
    char piece_type;
    

    printf("Enter piece type (k, b, p):\n");
    scanf('%c', &piece_type ); //segfaults here 
    /*other code */
    
    
    return 0;
}

CodePudding user response:

The first argument to scanf must be a pointer to a string. Most often it is given as a string literal, such as "%c", which is automatically converted to a pointer to its first element.

'%c' is not a string or a pointer to a string. It is a multicharacter constant, which is effectively an int constant.

Enable warnings in your compiler and elevate warnings to errors. With Clang, start with -Wmost -Werror. With GCC, start with -Wall -Werror. With MSVC, start with /W3 /WX.

CodePudding user response:

Instead of the format string in this call of scanf

scanf('%c', &piece_type ); //segfaults here
      ^^^^

you are using a multibyte integer character constant that has the type int. So the call invokes undefined behavior.

You need to use a string literal

scanf("%c", &piece_type ); 

Also it is better to include a leading space in the format string like

scanf(" %c", &piece_type ); 
      ^^^^

This allows to skip white space characters in the input buffer.

CodePudding user response:

As Eric said, you have to provide string (see reference) int scanf ( const char * format, ... );

One of the following should solve your problem:

  1. replace '%c' with "%c" so the code should look like this
...
    printf("Enter piece type (k, b, p):\n");
    scanf("%c", &piece_type );
    /*other code */
...
  1. use getchar() instead (reference - int getchar ( void );)
...
    printf("Enter piece type (k, b, p):\n");
    piece_type = getchar();
    /*other code */
...
  • Related