-
File Input
I have a file consisting of several lines, each line being
one of several different orders. For example, the file might look like this:
B Candy 50 (buy 50 candy)
S Milk (sell milk)
H 2 (hire 2 new employees)
Let's call Candy the 'second_parameter':
char second_parameter[10]
Note that I use enum {candy = 1, milk...} and do this later on:
if(strncmp("candy", second_parameter, MAX_STR_SIZE) == 0)
product = candy; // convert the string into enum value
else if(strncmp("milk", second_parameter, MAX_STR_SIZE) ==0)
product = milk;
I want to make sure that a malicious user cannot break the program by putting a very large string in the second file parameters, such as: B Candyyyyyyyyyyyyyyyyy 50. They could break the program during the input:
fin >> second_parameter;
What is the best way to prevent this sort of overflow? I'm sure I must be missing something very simple. Thanks in advance.
-
Why don't you take the value into a large buffer? The maximum a line can be within a text file is 80, I think.
[code]
#include <fstream.h>
int main(void)
{
const int BUFFER_LEN=80;
char FileName[]="Test.txt",Buffer[BUFFER_LEN];
fstream InFile(FileName,ios::in);
InFile.getline(Buffer,sizeof Buffer);
if(strlen(Buffer)=="condition etc")//check length etc
return 0;
}
-
still can't get use 2 these bloody code tags.
-
Interesting question.
Technically, Mr./Ms. Malicious can't foul up your "array" since it will be limited to ten chars regardless, but they could play havoc with memory outside of it, i.e. overflowing the bounds of the array.
You may try:
Code:
if(sizeof(second_parameter)>=MAX_STR_SIZE)
{
cout << "Input error!";
cin.ignore(sizeof(second_parameter), '\n');
}
At the least, that should protect the bounds of your array. 'strncmp' will take care of the validation.
:)
-
Thank you for your responses. I ended up solving the problem by reading the string into a buffer of length 80, and then using strncpy to copy the info read into my 'real' string.
One more question. Suppose I want to input an integer, but the user has placed a string in the file where I expect the integer. I can test for this with isdigit(), but since I am trying to read the whole string into an int:
fin >> quantity; // attempt to read string into an int variable
is there a chance that the info will overflow into another variable's space, causing data corruption?