简体   繁体   中英

Preventing buffer overflow when using fscanf

I'm using fscanf to read some values from a CSV file and I want to ensure that the data read into the values will not be too large and cause a buffer overflow.

My csv file has the format int,string,string and my code to read is below (I will fix the while condition later):

while(fscanf(f, "%d,%[^,],%[^,]", &inArray[i].ID, inArray[i].label, inArray[i].brand)/*insert while condition here*/

When using scanf I would specify the length like so to prevent overflow: scanf("%20f", example);

But if I try the same with the above: while(fscanf(f, "%d,%20[^,],%10[^,]", &inArray[i].ID, inArray[i].label, inArray[i].brand)/*insert while condition here*/

I get a crash when the code executes.

Try fscanf_s , this function has security enhancements. http://msdn.microsoft.com/en-us/library/6ybhk9kc(v=vs.90).aspx

You can't do that with fprintf when reading characters.

I would read the whole line first, eg, with getline() , locate the separators (or tokenize the line), and then parse the individual elements.

Btw., the reason for you crash might also be a wrong definition/initialization of inArray .

OP likely used the wrong width in the fscanf() .

Although OP did not post details about inArray[i] let's assume it was

struct {
  int ID;
  char label[20];
  char brand[10];
} inArray[100];

The format should then be

"%d,%19[^,],%9[^,]"

The width of 19 needs to be 1 less than the size of the destination, thus allowing a spot for the '\\0'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM