Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   C Programming (http://www.velocityreviews.com/forums/f42-c-programming.html)
-   -   Re: Checksum in a struct (http://www.velocityreviews.com/forums/t948360-re-checksum-in-a-struct.html)

Tim Rentsch 07-21-2012 06:42 PM

Re: Checksum in a struct
 
pozz <pozzugno@gmail.com> writes:

> 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?


What I think you want is a checksum for the physical value of
the struct, ie, a checksum that will match if the bytes are
written out (eg, to a file, or copied with memcpy()), and
then read back similarly (that is, by coping individual bytes).

Under that assumption, this approach will work okay, except you
need to take care to store the value in the 'checksum' memory
area so that it doesn't perturb the struct being checksum()'ed.
This can be done either by using a temporary variable and then
using memcpy() to get the value into ps.checksum, or by storing
indirectly through a pointer:

*&ps.checksum = checksum( ... );

I'm sure some people will say using memcpy() is safer. Certainly
most people would agree using memcpy() is no less safe. Alternatively
the checksum can be stored separately from the struct, so there is
no chance for storing it to affect the struct's physical value.

Personally, I would probably put the checksum either as the first
member of the struct (rather than the last), or outside the struct
altogether (as some others have explained more fully). However,
that's a stylistic choice, not a mandatory one: any of the three
can work, it's just a question of which one offers the best
combination of benefits and costs in your situation.


All times are GMT. The time now is 07:48 AM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.