2

PVS-Studio gave me a warning about this :

char c;
sscanf(line, "%d", &c);

I changed %d to %c but this created a bug because "c" now contains the ASCII value of the number and not the decimal one, so I went back to "%d".

So what's the correct specifier to ? is there another solution ?

1
  • 1
    char c; sscanf(line, "%d", &c); is already a bug, and a really, really bad memory-corrupting one at that. Commented Mar 29, 2018 at 13:27

2 Answers 2

5

c is a char. You asked to scan an int. PVS-Studio did right in warning you. Change the type of c to int and scan for a %d.

2
  • the char is from a legacy header, I can't change it.
    – Aminos
    Commented Mar 29, 2018 at 13:24
  • 3
    Scan to another variable and copy that to c. Don't scan directly to c as this may lead to you writing to memory you shouldn't.
    – Clearer
    Commented Mar 29, 2018 at 13:28
3

There are multiple solutions for your problem:

  • you can specify the correct destination type:

    char c;
    if (sscanf(line, "%hhd", &c) == 1) {
        /* successful conversion */
        ...
    }
    
  • you can use an intermediary variable:

    char c;
    int cc;
    if (sscanf(line, "%d", &cc) == 1) {
        /* successful conversion */
        c = cc;
        ...
    }
    
  • you can use different conversion function:

    #include <stdlib.h>
    ...
    char c;
    c = atoi(line);  // no error handling, return 0 if not a number
    

Note however that in all cases, if the numeric value converted by sscanf() or atoi() is outside the range of type char, the behavior is undefined. Most current system will just use the low order byte of the conversion result, but the C Standard does not guarantee it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.