views:

81

answers:

3

I have the following program,

int iIndex=0;
char cPort[5]={"\0"};
char cFileChar;
fopen_s(&fFile,"c:\\Config\\FileName.txt","r");
if(fFile !=0)
{
  cFileChar = getc(fFile);
  while (cFileChar!= EOF)
  {
    cPort[iIndex]=cFileChar;
    iIndex++;
    cFileChar = getc(fFile);
  }
iDIPort=atoi(cPort);
}

in the file I have 32000, but when the program execute and read from the file sometime its read fine and set iDIPort to 32000 but sometime it set the variable value to 320000.

Kindly help me to sort out this problem.

+4  A: 

You write the 5 characters into the cPort array. That's OK. But then, you use cPort as a parameter to the atoi function. This function expects a C zero-terminated-string as argument. As your cPort variable has no space to store this zero-value-char to indicate the end of the string, your code depends on what is right after the cPort variable in memory.

The easiest way to solve your problem is to define cPort as an array of 6 chars, and to assign 0 to cPort[5] right before calling atoi. But this won't solve the other issues of your code, the main being not to check if the number you read from the file has more than 5 figures.

Didier Trosset
OK Thanks Didier. This have been solve my problem.
Arman
A: 

Agree with Didier Trosset.

Another note: in the while loop you actually check the cFileChar variable for the first time before you assigned any valid value to it. Hence your program may surprise you once more.

You should either initialize it to some value (other than EOF) or change the loop into do-while.

valdo
Actually this is the part of program just for demonstration.
Arman
A: 

This program is a bit of a disaster waiting to happen. Changing the cPort array to length 6 is all very well, but what if someone puts something longer into FileName.txt? You've got yourself an instant buffer overflow and major security issue.

If you're expecting to read a maximum of 5 characters, make sure the program reads no more than 5 characters. This means terminating the while loop before EOF is reached, if necessary.

Another issue is that you're not checking that the characters from the file are what you expect. What if it doesn't contain numbers?

MatthewD