September 12th, 2011, 12:11 PM
How to check the length of inputted text before assigning to to a variable.
I was recently reading about buffer overflows, and noticed my code may have one. The code is
scanf( "%s",input ); //Scan for the first text.
Which is all very good, but the variable is:
And so if you typed 101 letters it would buffer overflow. I was wondering if there was a way to a) check the length of text before giving it a variable, or b) make a dynamically resizing variable (I have 1GB of RAM, which is 1024MB, 1048576KB, 1073741824 Bytes, 8589934592 bits, so it would be very difficult to fill up even 1 billion of them typing, so it would take a long time to fill it all (And more RAM = more bits, such as a 4GB PC would be 34359738368!))
char input; //Inputted text
September 12th, 2011, 12:34 PM
Read up on scanf(). I believe you can do something like this:
However, read the commonly asked questions for safe ways to read input (hint: fgets()).
September 12th, 2011, 01:16 PM
I am going to try the first answer, if that does not work I will look up fgets.
Originally Posted by mitakeet
Edit: scanf("%99s",input); did work, but for every 99 letters you enter it adds a new >. Not too much of a problem, unless someone falls asleep on the keyboard that should not happen. Still accepts commands on 3 chevrons. Thanks!
September 14th, 2011, 03:27 PM
If you actually checked out the functions you use you would know how to deal with newlines. Reading is a lost art but I recommend it highly if you can swing it.
Comments on this post
Functionality rules and clarity matters; if you can work a little elegance in there, you're stylin'.
If you can't spell "u", "ur", and "ne1", why would I hire you? 300 baud modem? Forget I mentioned it.
DaWei on Pointers Politically Incorrect.