0

I have a file from which I want to read data previously created by another program but I get an segmentation fault error. This is the programm.

typedef char Telemento[MAX_CHAR+5];

typedef struct{
   Telemento arraycola[NUM_ELEM];
   int inicio;
   int final;
}TCola;

typedef char TNombreImpresora[MAX_NOM_IMPR];

typedef struct{
   TNombreImpresora nombreimpresora;
   int numerodeficherosencola;
   TCola colaImpresora;
}TImpresora;

typedef struct{
   TImpresora impresora;
   int ocupado;
}TCelda;

typedef TCelda Tlistaimpresora[MAX_IMPR];



int main(){
    FILE *fp;
    int i=0;
    Tlistaimpresora listaimpresoras;



    fp=fopen("test.bin", "r");

    while(feof(fp)==0 && i<4){
       fread(&listaimpresoras[i].impresora, sizeof(listaimpresoras[i].impresora), (i+1), fp);
       listaimpresoras[i].ocupado=1;
       i++;
    }
    fclose(fp);


    return 0;   
}

Thanks for your time. If anyone needs more info please tell me.

Cypert
  • 159
  • 2
  • 11
  • Are you thinking 'i' is the file data pointer? Cf. http://stackoverflow.com/questions/10696845/does-fread-move-the-file-pointer – dwn Dec 27 '14 at 21:57
  • the function call 'feof()' is only valid AFTER reading from the associated file. Much better to use the returned value from fread() to control the while loop\ – user3629249 Dec 27 '14 at 21:59
  • Please check the result of `fopen` if it fails it returns `NULL` and you still try to read from it. – Iharob Al Asimi Dec 27 '14 at 22:04

4 Answers4

3

I think this line has an error (should be 1, not i+1):

fread(&listaimpresoras[i].impresora, sizeof(listaimpresoras[i].impresora), 1, fp);
kestasx
  • 1,091
  • 8
  • 15
3

Just change this

fread(&listaimpresoras[i].impresora, sizeof(listaimpresoras[i].impresora), (i+1), fp);

with this

fread(&listaimpresoras[i].impresora, sizeof(listaimpresoras[i].impresora), 1, fp);

you are not reading i + 1 items, just 1.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
0

replace (i+1) with 1 in the fread call

also change [1] to [i]

what you have happening is each read getting bigger and the last read overflowing the array.

what you want is each read the same size into a different array element.

Jasen
  • 11,837
  • 2
  • 30
  • 48
0

This line:

fread(&listaimpresoras[i].impresora, sizeof(listaimpresoras[i].impresora), (i+1), fp);

is a bit odd for a couple of reasons:

1) your only reading one instance of the struct

2) the real sizeof should be the sizeof the struct, not the sizeof some array entry.

suggest:

fread(&listaimpresoras[i].impresora, sizeof(Tlistaimpresora), 1, fp);

Also, the code is very obfuscated by the messy typedef declarations All these typedef's will make the code much more complicated than necessary. just define one struct with the appropriate number of instances for each field (or group of fields)

Roh
  • 127
  • 1
  • 12
user3629249
  • 16,402
  • 1
  • 16
  • 17