Re: Checksum in a struct

Discussion in 'C Programming' started by Tim Rentsch, Jul 21, 2012.

  1. Tim Rentsch

    Tim Rentsch Guest

    pozz <> 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.
    Tim Rentsch, Jul 21, 2012
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Eric Sosman

    Re: Checksum in a struct

    Eric Sosman, Jul 11, 2012, in forum: C Programming
    Tim Rentsch
    Jul 21, 2012
  2. Stefan Ram

    Re: Checksum in a struct

    Stefan Ram, Jul 11, 2012, in forum: C Programming
    James Kuyper
    Jul 25, 2012
  3. Re: Checksum in a struct

    , Jul 11, 2012, in forum: C Programming
  4. Re: Checksum in a struct

    , Jul 12, 2012, in forum: C Programming
  5. Peter Nilsson

    Re: Checksum in a struct

    Peter Nilsson, Jul 13, 2012, in forum: C Programming
    Peter Nilsson
    Jul 13, 2012

Share This Page