Two safer alternatives to scanf()

The scanf() function in C is dangerous because it’s susceptible to buffer overflows. If you create a ten character buffer char[10] and attempt to fill it with more than ten characters, the extra characters will overwrite whatever comes next in memory and possibly¬†smash your stack. One alternative is to use the m flag in your format string. Instead of using scanf(“%s”, char), use scanf(“%ms”, &char). The m flag will dynamically allocate enough memory to safely contain the input.

safer alternative to scanf(“%s”):

An older method of dynamically allocating enough memory to hold your string used “%a”, but it didn’t work for me on Ubuntu. Remember to free your pointer when you’re through with it, since the m flag dynamically allocated space for it. Also note that the second argument to scanf() is a pointer (&) when you use the m flag, whereas when you use “%s” scanf simply takes the string variable as its second argument.

Another more limiting alternative to scanf() with dynamic allocation is limiting the number of input characters scanf() will accept. For better or worse, this limits the size of our input to an arbitrary, predefined value (in this case, 20).

Using scanf() with a preset buffer size in your format string comes with a quirk. Any characters beyond the size of the buffer remain in the input buffer. If you get user input after your first scanf() and these characters are on the buffer, they will automatically be entered. The extra getchar() loop clears the remaining characters from the buffer, and clearerr(stdin) resets the state of your input buffer.

fgets() provides another way to fill a static buffer:

Unlike scanf(), fgets will return a newline with our input, so the \n character needs to be removed manually (in the for loop).

Incoming search terms:

Comments are closed.