Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is assigning a number too big to be represented in a bit field undefined behaviour

I have the following code:

#include <stdio.h>
#include <stdint.h>

enum nums {
    ONE,
    TWO,
    TWENTY = 20
};

struct field {

    uint32_t something : 4;
    uint32_t rest : 28;
};

int main(void) {

    struct field f;
    f.something = TWENTY;
    return 0;
}

On a powerpc 8241 running RTEMS 4.9.1, compiled with minGW GCC 3.4.5 (I know its old) this code will cause a segfault. The reason i have determined is that we are setting a number to big to be represented by a bit field to the bitfield in question. Since we have 4 bits it should only be able to represent 0 -> 15, and indeed when we set it with these numbers it works fine. Anything above and it crashes. I am unable to reproduce this behavior here, so my question is:

Is this undefined behavior? If so, is there a reference in a c standard that covers it?

Or is it more likely just a bug because of our very old compiler?

like image 229
Fantastic Mr Fox Avatar asked Oct 24 '25 15:10

Fantastic Mr Fox


1 Answers

This looks like a bug, at least in C99 this is well defined behavior, from the draft c99 standard section 6.2.6 Representations of types:

Values stored in unsigned bit-fields and objects of type unsigned char shall be represented using a pure binary notation.40

and later on in section 6.2.5 Types:

A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type.

like image 110
Shafik Yaghmour Avatar answered Oct 26 '25 06:10

Shafik Yaghmour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!