cpp-best-practices / cppbestpractices

Collaborative Collection of C++ Best Practices. This online resource is part of Jason Turner's collection of C++ Best Practices resources. See README.md for more information.
Other
8.02k stars 877 forks source link

Add GLIBCXX_ASSERTIONS to recommended compiler flags #158

Open Ryanf55 opened 7 months ago

Ryanf55 commented 7 months ago

When migrating legacy code from uint8_t my_arr[N] to std::array<uint8_t, N>, there are places where bracket access is used. This does not perform bounds checking, even at compile time.

For example, you could construct an array with 6 elements, then access element 42 at runtime with no errors, even with all the flags enabled that are currently recommended. https://godbolt.org/z/3KWqe1vbs

Even if you set -Weverything and compile in clang, it's not caught.

I figured out you can enable bounds checking on bracket access with GLIBCXX_ASSERTIONS https://gcc.gnu.org/onlinedocs/libstdc++/manual/using_macros.html

There are runtime costs with bounds checking, so it should not be enabled in production, however this would be great flag to add to a debug build that is tested in CI.

With this enabled in debug mode, you seem to get the best of both worlds.

#include <array>
#include <iostream>

int main() {

    std::array<double, 6> a;
    std::cout << "The UB value of a is " << a[42] << std::endl;
    return 0;
}