Search code examples
cunsigned-integerunsigned-long-long-int

Architecture agnostic code


I have this piece of code where the aim is to determine if the packet received is valid or not:

size_t offset_to_a, offset_to_b;
u_int32_t file_name_length;
u_int32_t packet_length;

if ((offset_to_a + offset_to_b + file_name_length) > packet_length) {
    // Invalid packet
}

size_t is u_int64_t perhaps because the cpu is a 64-bit one.

Now when file_name_length has a value 0xFFFFFFFF (which is invalid), then the packet is deemed invalid.

But if size_t becomes u_int32_t because of the underlying architecture, then for the same value of file_name_length, the condition fails because the value would wrap around, and the packet is deemed valid.

How can I make this condition generic enough to work on both 32/64-bit architectures?

Thanks!


Solution

  • The trick is to only use subtraction, and only subtract after verifying that the subtraction won't wrap. Something like this:

    if (offset_to_a > packet_length || packet_length - offset_to_a < file_name_length) {
        // invalid packet
    }
    size_t remain = packet_length - offset_to_a;
    if (offset_to_b > remain || remain - offset_to_b < file_name_length) {
        // invalid packet
    }