Safe Coding Practices – scanf()

When it was pointed out to me that using the scanf() functions in my online teaching material was an “unsafe coding practice,” I thought, “Well, duh!” I’ve never been a fan of scanf(); it’s an ugly function.

I recall when I first learned to code. The scanf() function frustrated me. In fact, one of the first functions I coded in C, one that I used over and over, is my own input() function to read a string of text; I’ve never used scanf() beyond my books or courses.

Here is what I wrote in a blog post in October 2016:

I’m not a fan of the scanf() function, despite how handy it can be. It’s a great teaching tool, but for a program that accepts string input, you need to use fgets() instead.

The post from April 2014 is titled “scanf() the Bastard.”

Yes, I have no love for the function, but how specifically is it an “unsafe” programming practice? The issue raised was that it’s not suited for numeric input. That’s one useful feature scanf() has, especially when writing a program to teach C; it replaces a bunch of other functions required to convert string input to a numeric value.

The issue raised is the “undefined behavior” of scanf(), specifically when input isn’t what’s requested. I mention this vulnerability in my teachings: You must trust that the user types the input requested or the code goes bonkers, especially for numeric input.

#include <stdio.h>

int main()
{
    float balance;

    printf("Enter your bank balance: ");
    scanf("%f",&balance);
    printf("Half your balance is %.2f\n",
            balance/2);

    return(0);
}

If you run this code and type a value, it works. Type a string as input and you see:

Enter you bank balance: none of your business
Half your balance is 0.00

If you type NAN, you get:

Enter you bank balance: NAN
Half your balance is nan

The value NAN is numeric code for “not a number”; INF is code for “infinity.” These are both “values” interpreted by the C program. NAN can also be output, for example, when you try to obtain the square root of a negative value.

The fscanf() function, which reads values from a file, also suffers from the same flaws as scanf(). Yet, as a teaching tool, I believe using the function is okay. For code released to the wild, don’t use fscanf(), either.

These issues are important, and I believe I fully address them in my courses. For details from the Software Engineering Institute’s concerns regarding various scanf() weaknesses, click here.

Leave a Reply