2015-10-21 86 views
2

我有以下代碼:是分配數量太大的位域表示未定義行爲

#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; 
} 

在運行RTEMS 4.9.1一個PowerPC 8241,使用MinGW GCC 3.4.5(我編譯知道它的舊)這段代碼會導致段錯誤。我確定的原因是,我們正在設置一個大的數字來表示一個位字段的位字段。由於我們有4位,它應該只能表示0 - > 15,事實上,當我們用這些數字設置它時,它工作正常。任何以上和它崩潰。我無法複製此行爲here,所以我的問題是:

是這樣的未定義的行爲?如果是這樣,是否有涵蓋它的c標準中的參考?

還是更可能只是一個錯誤,因爲我們的很老舊的編譯器?

+0

這將是有趣與'-S'標誌編譯查看生成的彙編語言。 – lurker

+0

@ lurker,大概可以安排... –

+0

這個問題已經在這裏解答:http://stackoverflow.com/questions/2151305/gcc-warning-large-integer-implicitly-truncated-to-unsigned-type#2151321 。如果向GCC添加'-Werror'標誌,那麼應該預期輸出結果爲:'錯誤:大整數隱式截斷爲無符號類型[-Werror = overflow] f.something = TWENTY;' – BufferOverflow

回答

3

這看起來像一個錯誤,至少在C99這是有規定的行爲,從C99標準草案部分的類型6.2.6交涉:

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

,後來在第6.2.5類型:

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.