Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[C] Tip: Avoiding Buffer Overflows With scanf()
If you are choosing to parse strings with scanf(), maybe because you don't want to deal with the issues of '\n' with fgets() (even though there are still issues with scanf() aside from it being a more expensive function to call for grabbing a string without any special format because the format string needs to be read by the function to determine what data goes into each following variable argument), then you should be using a length modifier. The issue here is that you aren't able to use a wildcard, and you can't just concatenate some numeric value or variable directly into the string like in other languages... You would have to programmatically parse it into the format string passed to the function which is a bit of work, or just hardcode it into the string literal, which may not always be the best case scenario if you want something to be a bit easier to manage should you ever have to change the size of the buffer, because then you have to go in and manually change the value within the string too. An alternative to make this easier is to use macros.

#include <stdio.h>

#define STRTOKEN(x) #x
#define STR(x) STRTOKEN(x)
#define MAX_LENGTH 100

int main(void)
  char buf[MAX_LENGTH + 1];
  scanf(" %" STR(MAX_LENGTH) "s", buf);
  return 0;

What happens here is we've defined a MAX_LENGTH constant to be the max length of the input (without the null terminator). So we allocate a buffer with MAX_LENGTH + 1 to allocate enough space for the terminator, and tokenize this value into a string using the preprocessor so that it can be part of the format string before the code is compiled.

In this case, our buffer allows for 101 elements, where index [100] is reserved for the null terminator, and our scanf() call with the preprocessed format string would then look like:
scanf(" %100s", buf);

Perfect! Now we can modify the size of our allocated buffer and the format string easily all by just changing one constant value here:
#define MAX_LENGTH 100
Good tutorial and nice demonstrations, good to see someone posting tutorials again. Rep for you!
Not really a tutorial but a strategy/tip for programming in C and parsing strings with a specific function.
(05-30-2015, 08:33 PM)bitm0de Wrote: Not really a tutorial but a strategy/tip for programming in C and parsing strings with a specific function.

Ahh I see, well we still need more informative threads like these none the less.
[Image: 4.png]

Forum Jump:

Users browsing this thread: 1 Guest(s)

Powered by © 2002-2020 MyBB Group.
Theme by CreWix. Fixed by Tomik. Customized for Aeowulf.