简体   繁体   中英

Program stop reading file using fgets

It would be nice if anyone could help me with my 'program'. I am trying to read csv file and move it to 2D array. It stops on 17th line(out of 200).

    int main ()
{
   FILE * pFile;
   double **tab;
   char bufor [100];
   int i=0;
   tab = (double**)malloc(sizeof(double*));

   pFile = fopen ("sygnal1.csv" , "r");
   if (pFile == NULL) printf("Error");
   else 
        while (fgets (bufor , 100 , pFile))
            {
            tab[i] = (double *) malloc(2 * sizeof(double));
            sscanf(bufor, "%lf, %lf,", &tab[i][0], &tab[i][1]);
            printf("%lf.%lf.\n",tab[i][0],tab[i][1]);  //It's here only for testing
            i++;
            }
    printf("number of lines read %d\n",i);
    fclose (pFile);
    system("PAUSE");
    return 0;
}

You haven't completely allocated memory for tab yet. You've just allocated one (uninitialised) pointer. When i > 0 you're into Undefined Behaviour. You need to allocate at least as many elements as there might be lines in your file, eg

   tab = malloc(sizeof(*tab) * MAX_LINES);

or use realloc after each iteration to increase the number of elements.

tab = (double**)malloc(sizeof(double*));

You're only allocating 1 element in this array. All other accesses are writing over unallocated chunks of memory and probably causing damage.

Try realloc ing periodically.

You created place for only one double * in tab, if you know the number of lines you want to store, then do :

tab = malloc(sizeof(*tab) * NB_LINES);

Also, don't cast the return of malloc.

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