Re: Checksum in a struct
pozz <firstname.lastname@example.org> writes:
> Il 12/07/2012 17:08, Eric Sosman ha scritto:
>> If you want to write a struct and a checksum to a file and
>> verify the checksum when you read it back, keep the checksum as
>> a separate variable and don't put it inside the struct.
> Could I ignore the "randomness" of the padding bytes? I read that
> the padding bytes can be randomly changed even assigning a value to a
> field of the struct. My application should work in this way:
> - at startup, read the configuration file, calculate and verify the
> checksum: if it isn't correct, use a default struct;
> - when a field changes (after assigning it the new value), calculate
> the new checksum and save both (struct and checksum) to the file;
> - during the normal execution of the application, the fields of the
> struct are accessed many times.
> In this situation, could I calculate the checksum on the entire
> memory area of the struct (with padding bytes)? [snip]
Yes, provided (1) if the whole struct is updated, either you
calculate a new checksum from scratch or you make sure the
padding bytes are copied also (eg, by using memcpy()) and
use the checksum of the source struct, and (2) the checksum
is stored in a way so as not to perturb the struct's padding
bytes (this can be done by putting the checksum outside the
struct in question, or by updating an in-struct checksum
using, eg, memcpy()).
This question was asked fairly clearly and obviously is the most
important one to answer; I don't know why it wasn't responded
to more directly.
You are right that reading a struct or its members has no
effect on its padding bytes.