[Bug c++/105746] New: vector<union>::resize causes Warray-bounds when optimizer uses __builtin_memcpy or __builtin_memmove

albrecht.guendel at web dot de gcc-bugzilla@gcc.gnu.org
Fri May 27 00:08:35 GMT 2022


https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105746

            Bug ID: 105746
           Summary: vector<union>::resize causes Warray-bounds when
                    optimizer uses __builtin_memcpy or __builtin_memmove
           Product: gcc
           Version: 10.1.1
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: albrecht.guendel at web dot de
  Target Milestone: ---

https://godbolt.org/z/YP5aWjbzM

>From version 10.1 to trunk (both arm-none-eabi, x86-64)
Compiling with: -O3 -Wall -Wextra -Werror

The following code:

#include <vector>

union U //works if is struct
{
    unsigned char data;

    //required to construct from 0xff
    U(const unsigned char raw): data(raw) {} 

    //required by vector::resize
    U(const U& other): data(other.data) {} 
};

auto bug()
{
    std::vector<U> v;
    v.resize(100, 0xff);
    return v;
}

produces the warning:

void* __builtin_memcpy(void*, const void*, long unsigned int)' offset 100 is
out of the bounds [0, 100]

This is the most minimum example i have found.
Noticeable: 
- it only happens when using O3
- it also happens when the compiler decides to use __builtin_memmove instead
(havent found a good minimum example for that; my working-code results in using
memmove)
- replacing the union with a struct/class resolves the issue
- the bug also occurs when resizing with some compile-time known U, instead of
an integer constant (it does not matter which copy-constructor is called by
vector::resize, just that the optimization to __builtin_memcpy is possible).
- clang and other compilers complain about the copy-constructor being
deprecated in this code example. [this one: U(const U& other): data(other.data)
{} ].
And, indeed, replacing it with U(const U& other) = default; actually resolves
the issue. (but maybe the memcpy-optimization is just not triggered?)


I think this is worth investigating because this either hints at some bad
constant propagation or bounds-check. Basically, I dont know, if the warning
triggers erroneously or if the warning has merit due to an optimization bug.
According to other compilers, the code is bad/deprecated.. but gcc does not
warn (and I dont know why other compilers warn here).
In detail, clang says: definition of implicit copy assignment operator for 'U'
is deprecated because it has a user-declared copy constructor
[-Wdeprecated-copy]


More information about the Gcc-bugs mailing list