View Single Post
  #37 (permalink)  
Old 07-21-2012, 06:44 PM
Tim Rentsch
Guest
 
Posts: n/a
Default Re: Checksum in a struct

Eric Sosman <esosman@ieee-dot-org.invalid> writes:

> On 7/11/2012 10:56 AM, pozz wrote:
>> I have a function that computes a 16-bit checksum (following whatever
>> algorithm) of a memory space:
>>
>> unsigned int checksum(const void *buffer, size_t size);
>>
>> I want to embed this checksum in a struct:
>>
>> struct PStruct {
>> int x;
>> unsigned int y;
>> char z[13];
>> ...
>> unsigned int checksum;
>> };
>>
>> How to use the checksum() function above? I propose:
>>
>> struct PStruct ps;
>> ...
>> ps.checksum = checksum(&ps, offsetof(struct PStruct, checksum));
>>
>> Is there a better mechanism?

>
> You'd better hope so :-)
>
> A problem with the approach you've outlined is that the
> checksum computation will include the values of any padding
> bytes -- the size of `z' in your example almost begs for some
> padding bytes to be inserted. [snip elaboration]


You're assuming he wants a checksum on the "logical
value" of the struct. If what he wants is a checksum
on the physical value of the struct -- which appears to
be what he does want -- then this approach will work fine
(provided of course care is taken so that storing the
checksum will not perturb the padding bytes, which I
have already addressed in an earlier reply).
Reply With Quote