: int main (void)
: int BUFSIZE = 100;
: int i, Index;
: FILE *Fp;
: char Buffer[BUFSIZ];
: char * P, * NewLine;
: Fp = fopen("filename","r");
: if (!Fp)
: printf("Not able to open file!\n");
: for (i=1; fgets(Buffer,BUFSIZ,Fp) ; i++)
: Index = strtod(Buffer,&P);
My first question is, why are you using strtod() for an int? It would seem to me that strtol() would be a better choice. That having been said, are you positive
that you have #included <stdlib.h> in your preprocessor directives? I seem to recall my own similar errors when I have used functions that return double
, but an oversight on my part caused me to forget their prototype, and the compiler just assumed int
. That would be some UB for you, and it could easily result in some very strange occurences.
Another option you could try, would be to test 'errno' for ERANGE, and then display 'Buffer' with perror() (all three from <errno.h>). Additionally, using an int
precludes you from testing for HUGE_VAL(<math.h>), which strtod() returns on error. If you changed 'Index' to long
(and then your printf() format-specifiers), you could test for LONG_MIN or LONG_MAX (from <limits.h>) on return from strtol(), and then 'errno' for ERANGE. With what you are doing right now, you might as well just use atof(), which along with its cousin atoi(), are not very good at error recognition.
: while (isspace(*P))
Oops! For portability's sake (and eradicating more UB possibilities):
while ( isspace((unsigned char)*P) )
: The strange part is that it works fine as a stand alone program, but when used as part of an algorithm set for a system, strod() returns a bad index...
: Line 1: Bad index -268450352 for label 1 QA
: This is using the same exact same input file in both cases. Why would it work sometimes and not others?
I am inclined to agree with Mr. Tetz on this one, but only if you have actually included a prototype for strtod(). The behavior you describe, and the output you have shown, well... *snif* *snif* ... smells like UB to me.