Search code examples
cstdio

Why does scanf("%s", val); return null?


I'm trying to read a single character into a char* called val and when I use scanf() it returns null. Here is my code:

#include <stdio.h>

int main(int argc, char *argv[])
{
    char *val;
    if (argc == 2)
    {
        val = argv[1];
    }
    else
    {
        scanf("%s", val);
    }
    printf("Val = %s", val);
}

If I try to use malloc(), it will continuously read from standard input if the input is one character long, which is how long I want my input to be.


Solution

  • Why does scanf("%s", val); return null?

    scanf() needs to read input into a valid location.


    With scanf("%s", val);, code passes to scanf() an uninitialized pointer val to scanf(). This leads to undefined behavior (UB).

    Instead, pass a pointer to memory ready to accept the input.

    • Pass a pointer to a location ready to accept characters.

    • Use a width to avoid overrun.

    • check the return value.

        char *val;
        char s[100+1]; 
        if (argc == 2) {
          val = argv[1];
        } else {
          if (scanf("%100s", s) != 1) {
            fprintf(stderr, "Invalid input\n");
            return -1;
          }
          val = s;
        }
    

    To read a single character use:

    char ch; 
    if (scanf("%c", &ch) != 1) {
      fprintf(stderr, "Invalid input\n");
      return -1;
    }