Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it UB to access 'padded' bytes?

If I have an object like this one:

struct {
    uint32_t n;
    uint8_t c;
} blob {};

then there will be 3 'padded' bytes.

Is it UB to access the padded bytes? E.g:

uint8_t * data = reinterpret_cast<uint8_t*>(&blob);
std::cout << data[4] << data[5] << data[6] << data[7];

I first assumed this would probably be UB, but if that's true then a memcpy would be UB as well:

memcpy(buf, &blob, sizeof(blob));

My specific questions are:

  • Is it UB to access padded bytes?
  • If no, then does that mean the values are defined as well?
like image 932
StackedCrooked Avatar asked Feb 06 '13 20:02

StackedCrooked


1 Answers

No, it's not UB to access padding when the entire object has been zero-initialised (the standard says in §8.5/5 that padding is initialised to 0-bits when objects are zero-initialised) or value-initialised and it is not a class with a user-defined constructor.

like image 91
Seth Carnegie Avatar answered Oct 26 '22 00:10

Seth Carnegie