1

I have a serious problem with this code:

double wczytanie(){
FILE *plik;
char znak;
int i=0; 
int x=0;
float **tab;
char nazwapliku[100];
printf("Podaj nazwe pliku: ");
scanf("%s", nazwapliku);
plik = fopen(nazwapliku,"r");   
while(!feof(plik)){
znak=fgetc(plik);
    if(znak=='\n') {
    i++;
    }
}


tab=(float**)malloc(sizeof(float*)*3);
    for(x=0;x<3;x++){
        tab[x]=(float*)malloc(sizeof(float)*i);
    }   

   rewind(plik);     

for(x=0;x<=i;x++){
fscanf(plik,"%f %f %f", &tab[0][i], &tab[1][i], &tab[2][i]);
    printf("%f %f %f\n", tab[0][i], tab[1][i], tab[2][i]);
    }
fclose(plik);

The file is read properly, values are printed, but it crashes afterwards, returnig code 255, or 3221226356. When I removed the "fscanf" line it seemed to work without crashing, but well, it didn't read anything... How can I fix this? Any ideas what may cause the crash?

ikurek
  • 604
  • 11
  • 27
  • 1
    See [`while (!feof(file))` is always wrong](http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong) for one of the problems with the code. Another set of problems is that you don't check that the input functions succeed, nor that the file is opened successfully, nor that the memory allocations succeed. – Jonathan Leffler Jun 11 '16 at 19:23
  • 1
    `for(x=0;x<=i;x++){` -->> `for(x=0; x< i ;x++){` and `&tab[0][i]` --> `&tab[0][x]` – wildplasser Jun 11 '16 at 19:24
  • when asking a question about a run time problem: post code that cleanly compiles The posted code does not even contain any function definition, not the required `#include` statements. – user3629249 Jun 13 '16 at 15:18

1 Answers1

2
tab[x]=(float*)malloc(sizeof(float)*i);

Due to way you allocate memory above, you seem to have array access out of bounds on below line. You can only access indexes (of your second dimension) up to i, e.g., 0....i-1, not including it.

Here:

fscanf(plik,"%f %f %f", &tab[0][i], &tab[1][i], &tab[2][i]); // can't access i-th element

Probably you meant x instead of i above, but then you need to make the condition inside for tighter (e.g. x<i).

Also, you don't need to cast result of malloc.

Giorgi Moniava
  • 27,046
  • 9
  • 53
  • 90