Search code examples
arraysccounteransi-c

C counter resets unexpectedly


The code below is supposed to take the data from the string s and split it into the double array data with white space as a delimiter. The j counter unexpectedly resets when it should increment to terminate the function

The char *s, being passed to the function is

0.0000000E00     0.0000000E00       -1.9311798E+03       8.0321814E+02       8.0294336E+02  

The diagnostic printf function below prints:

0.000000 | 1
0.000000 | 2
-1931.179800 | 3
803.218140 | 4
802.943360 | 1

It causes the program to crash

void split_data(char *s, double *data, int fields) {
  char buff[DATA_MAX];
  int j = 0, i;

  for(; *s; *s++) {
    while(*s == ' ' || *s == '\t') /* trim leading white space */
      *s++;

    i = 0;
    while(!(*s == ' ' || *s == '\t'))
      buff[i++] = *s++;
    buff[i] = 0;

    data[j++] = atof(buff);
    printf("%lf | %d\n", data[j-1], j);

    if(j == fields)
      return;
  }
}

Solution

  • Your loop:

       while(!(*s == ' ' || *s == '\t'))
          buff[i++] = *s++;
    

    should also contain a test for the end of the string s. For example while(!(*s == ' ' || *s == '\t') && *s) ....

    Otherwise, buff will continue to be filled with 'noise' until it overflows. And then other variables on the stack will begin to be clobbered, such as j. But the behavior is very compiler-dependent.