Author Topic: fgets, gets, scanf  (Read 5176 times)

Offline iAnzu

  • Jr. Member
  • *
  • Posts: 4
fgets, gets, scanf
« on: June 01, 2019, 05:00:51 PM »
Hi,

I'm doing a little nasmx86 program, and at many places I need to get user input, with an specified length.
I'm using Linux  and building as:
nasm -f elf32 -o
gcc  -m32 -o

I would like to know if the user entered more/less than the expected, in which case I would like to clear stdin, and tell the user to try again.


gets:
The problem with this, is I can't control how much input the user will enter, I'm using gets, and then copying "n" bytes to another string, so if I want a 5 char name, and the user enters "123456", it won't cause any problem, because, gets has a large reserved memory to allocate it, then I copy the first 5 bytes to another place and it's done. But it doesn't look good visually.

scanf:
Using special arguments ("%3s") solves the problem, but if the user entered more than the allowed digits, those digits will stay in stdin, and will be used when there's a new call that uses stdin.

fgets:
Same problem with scanf...

I've tried...
- For the case of fgets, and scanf, if the user entered more than the allowed digits I can do a dummy call to gets, to flush stdin, but if the user entered less than the allowed digits, the dummy call to gets is useless, and will make the program ask for non required additional input.

Offline iAnzu

  • Jr. Member
  • *
  • Posts: 4
Re: fgets, gets, scanf
« Reply #1 on: June 01, 2019, 09:02:14 PM »
Something I came up with is, since I know the length of the string to be entered, I know where the "null" character will be (with gets), therefore, I just check if the null character is added , if not, I ask again for the string.  ;D

This auxiliar buffer's length is 123 bytes, so if the user enters more than that, the program will break... but at least is more serviceable! I think


Offline Frank Kotler

  • NASM Developer
  • Hero Member
  • *****
  • Posts: 2667
  • Country: us
Re: fgets, gets, scanf
« Reply #2 on: June 02, 2019, 12:31:32 AM »
"gets()" is dangerous. Please don't use it - and don't write a gets-equivalent. A big buffer just gives attackerz lots of room to play.

"sys-read" from the keyboard always ends in a linefeed (10). Check the last byte entered, and if it's not 10. read a byte at a time into a dummy buffer until it shows up. That's how I'd handle it.

Best,
Frank