I have the following code on Godbolt https://godbolt.org/z/YfobsnMra
And the same code on my machine
#include <string>
#include <cstdio>
int main() {
std::string s;
s[-8] = 42;
printf("size: %d\n",s.size());
}
While this code compiles, it does not run because it appears that an assert
is failing:
g++ cursed.cpp -o cursed
/usr/src/debug/gcc-build/x86_64-pc-linux-gnu/libstdc++-v3/include/bits/basic_string.h:1221:
std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::reference
std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::operator[](size_type) [with _CharT =
char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>; reference = char&;
size_type = long unsigned int]: Assertion '__pos <= size()' failed.
[1] 31811 IOT instruction (core dumped) ./cursed
If I run g++ -v
I get the following output:
Using built-in specs.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-pc-linux-gnu/12.2.0/lto-wrapper
Target: x86_64-pc-linux-gnu
Configured with: /build/gcc/src/gcc/configure --enable-languages=c,c++,ada,fortran,go,lto,objc,obj-c++,d
--enable-bootstrap --prefix=/usr --libdir=/usr/lib --libexecdir=/usr/lib --mandir=/usr/share/man
--infodir=/usr/share/info --with-bugurl=https://bugs.archlinux.org/ --with-build-config=bootstrap-lto
--with-linker-hash-style=gnu --with-system-zlib --enable-__cxa_atexit --enable-cet=auto
--enable-checking=release --enable-clocale=gnu --enable-default-pie --enable-default-ssp
--enable-gnu-indirect-function --enable-gnu-unique-object --enable-libstdcxx-backtrace
--enable-link-serialization=1 --enable-linker-build-id --enable-lto --enable-multilib
--enable-plugin --enable-shared --enable-threads=posix
--disable-libssp --disable-libstdcxx-pch --disable-werror
Thread model: posix
Supported LTO compression algorithms: zlib zstd
gcc version 12.2.0 (GCC)
How can I get the same behavior as Godbolt where it outputs 42
? What compiler configuration am I missing to have the same behavior as Godbolt.