开发者

16bit bitfield leads to *read from uninitialised memory* warning

I have this typedef:

typedef union
{
    unsigned Value;
    unsigned Timestamp:16;
} BITFIELD;

and get this compiler warning:

BITFIELD bitfield;

// read from uninitialised memory - may result in unexpected behaviour
bitfield.Timestamp = 12;

Now, the warning disappears when I use a short instead of the bitfield:

typedef union
{
    unsigned Value;
    unsigned short Timestamp;
} DATATYPE;

I am not sure what to think about this warning - I don't understand it. There is no uninitialised memory involved and n开发者_开发知识库o read operation, too. IMHO the compiler (VisualDSP++ 5.0 C/C++ Compiler) is wrong here. The warning disappears also, when I use a :32 bitfield for Timestamp.

Is there anything I didn't realize? Can I safely ignore this warning?


How big is an unsigned int on your system?

The only thing I can think of that may cause this is if the 16 bit bitfield forms only part of the Timestamp variable (if, for example, an unsigned int is 32 bits wide).

In other words, maybe the compiler is turning that into:

Timestamp = (Timestamp & 0xffff0000) | 12;

which would cause that problem if Timestamp were uninitialised.

That fits in with:

  • using a 16-bit short since the code would probably just then become Timestamp = 12;.
  • using :32 since, it expands the bitfield to the point where a direct assignment is also possible.

Pure supposition on my part but, discounting a brain-dead compiler, that's the best I can come up with (if it's true, it's probably still brain-dead but in a different way).

FWIW, gcc doesn't complain even with -Wall.


I agree that the compiler seems to be a little too eager to gives this warning in this case (I wonder if what is missed here is that what remain of the 32 bit word used for the 16 bits field is all padding).

I'm more use to get this from tools like purify.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜