Hello,

we ran into an issue with the following (rather benign) C++ snippet:

#include <atomic>
#include <mutex>

struct Foo {
  void Bar() ;

  std::mutex some_lock;
  std::atomic<uint8_t> some_number;
};

void Foo::Bar() {
        some_lock.lock();
        some_number++;
        some_lock.unlock();
}

When compiling this with a recent GCC on Linux (!) with the following flags

g++ -fsanitize=undefined  -O2 -Werror -c test.cpp -o test.o

The following error is thrown:

In member function ‘std::__atomic_base<_IntTp>::__int_type
std::__atomic_base<_IntTp>::fetch_add(__int_type, std::memory_order)
[with _ITp = unsigned char]’,
    inlined from ‘std::__atomic_base<_IntTp>::__int_type
std::__atomic_base<_IntTp>::operator++(int) [with _ITp = unsigned
char]’ at /usr/include/c++/12/bits/atomic_base.h:369:25,
    inlined from ‘void Foo::Bar()’ at test.cpp:13:13:
/usr/include/c++/12/bits/atomic_base.h:618:34: error: ‘unsigned char
__atomic_fetch_add_1(volatile void*, unsigned char, int)’ writing 1
byte into a region of size 0 overflows the destination
[-Werror=stringop-overflow=]
  618 |       { return __atomic_fetch_add(&_M_i, __i, int(__m)); }
      |                ~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~

Interestingly, the error disappears with -O0 or -O1 which makes me
think it's a bug related to optimization.

Thanks

Hannes

Reply via email to