5

I'm having troubles in my college homework, I'm coding in c++ some sorting methods, and this just happened:

int nufi = 0, d;
cout << "nufi  value: " << nufi << endl;

d  = fread(&item, sizeof(ItemType), 1, stripes[nStripe].arq);

cout << "nufi value: " << nufi << endl;

That was suposed to print: nufi value: 0 nufi value :0 But, instead, is printing: nufi value: 0 nufi value: 541151813

Basically, any integer variable that passes by the fread is being changed;

I have tried to change variables names, change opened files and every test that I think and the error persist, not always with that value, when I change variables names, the number changes too, only when I remove the fread, the error disappears.

The rest of the code is fine and tested, the file opening, structs, keys, etc.

Anyone have any idea what may be happening?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Dk Ribeiro
  • 113
  • 8

1 Answers1

2

You are getting undefined behaviour, and changing variable names will not help. You have a type problem, where item is clearly not of type ItemType. Thus, fread is writing extra bytes onto your stack where other variable storage lives.

Change the call to this:

fread( &item, sizeof(item), 1, stripes[nStripe].arq );

You have not actually shown its type, but I'm willing to bet that it's ItemType*. In which case, you would have a slightly different syntax:

fread( item, sizeof(ItemType), 1, stripes[nStripe].arq );
//     ^ Note reference removed because item is a pointer to ItemType.
paddy
  • 60,864
  • 6
  • 61
  • 103