Sarvadi Sarvadi - 1 year ago 73
C++ Question

std::array - 'buffer of size n will be overrun', only in VS

constexpr auto CHUNKS_X = 5, CHUNKS_Y = 5, CHUNKS_Z = 1;
std::array<std::bitset<CHUNKS_X>, CHUNKS_Y> ys;
std::array<decltype(ys), CHUNKS_Z> zs;
if (CHUNKS_Z > 1)
zs[0] = ys;
// = ys; //this works
zs[1] = ys; //this doesn't work
for (auto &x : zs[1])
for (auto z = 2; z < CHUNKS_Z; z++)
zs[z] = zs[z - 2];

The line
zs[1] = ys;
gives me

error C4789: buffer 'zs' of size 20 bytes will be overrun; 20 bytes will be written starting at offset 20

But only when compiling in VS. Compiling on the command line gives me no such error, nor does using = ys;
instead. Another thing of note is that MSDN says that this should be a warning, not an error.

I realize this might be a subtle compiler flag issue but I haven't the slightest clue where to start looking.

Microsoft (R) C/C++ Optimizing Compiler Version 19.00.23506 for x86

Answer Source
std::array<decltype(ys), CHUNKS_Z> zs;

is equivalent to

std::array<decltype(ys), 1> zs;

meaning zs is an array with 1 element;

arrays in general are zero-based meaning the first element is at zs[0], and there are no more elements so zs[1] requires that the arrays will have a second element which it doesn't in your example.

Since you check if (CHUNKS_Z > 1) there should not be any problem since you can't reach the line zs[1] = ys; and you won't get any issues.

If I change CHUNKS_Z to 2 I don't get any errors in VS15

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download