• IMPORTANT: Welcome to the re-opening of GameRebels! We are excited to be back and hope everyone has had a great time away. Everyone is welcome!

[C] Tip: Avoiding Buffer Overflows With scanf()

bitm0de

Active Member
Joined
May 24, 2015
Messages
13
Reaction score
0
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.

Code:
#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:
Code:
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:
Code:
#define MAX_LENGTH 100
 

Toxique

Well-Known Member
MOTM
Joined
Jan 27, 2012
Messages
3,910
Reaction score
11
Good tutorial and nice demonstrations, good to see someone posting tutorials again. Rep for you!
 

bitm0de

Active Member
Joined
May 24, 2015
Messages
13
Reaction score
0
Not really a tutorial but a strategy/tip for programming in C and parsing strings with a specific function.
 

Toxique

Well-Known Member
MOTM
Joined
Jan 27, 2012
Messages
3,910
Reaction score
11
bitm0de said:
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.
 
Top