3

Countless time I wrote code that generated a segmentation fault after accessing an std::vector or an std::string outside its memory:

std::string test{"hello!"};
std::cout << test[12] << std::endl;

This is an error that could be caught at run-time in non-optimized/debug builds, with a small additional cost of a simple assertion. (But since we're building without -DNDEBUG and without -O3 we're not expecting to get maximum performance.)

Is there any reason why std::string::operator[] isn't implemented like this?

Does the standard forbid use of asserts in library code?

char std::string::operator[](std::size_t i)
{
    // `assert_with_message` only exists in debug mode

    #ifndef NDEBUG
        assert_with_message(i < this->size(),
            "Tried to access character " + std::to_string(i)
            + " from string '" + *this + "' of size " 
            + std::to_string(this->size()));
    #endif

    return data[i];
}

It would be really helpful to compile the program without -DNDEBUG and see something similar to this message at runtime:

Assertion fired: Tried to access character 12 from string 'hello!' of size 6.

Press (0) to continue.

Press (1) to abort.

Note that by the term assert I'm referring to a development/debug build check that should be completely removed/optimized-out from release/optimized builds.

1
  • It is the case in several implementations, but protected by a different macro than NDEBUG so you can separately enable your own asserts or those of the standard library. Mar 25, 2015 at 12:47

4 Answers 4

5

Several implementations of the standard library do provide such checks in debug mode, but debug mode is not controlled by NDEBUG. For libstdc++, you need -D_GLIBCXX_DEBUG (see the doc).

3

What you did was Undefined Behavior. As anything is allowed at that point, firing an assert is also OK. This is a Quality of Implementation thing, and it looks like libstdc++ isn't so good here.

5
  • 1
    @MarcGlisse: really nice - this is what I was looking for. Mind writing an answer so that I can accept it? Mar 25, 2015 at 12:54
  • 2
    Bit of a shame that they don't follow the NDEBUG convention. Sure, you'd still want a way to override libstdc++ debug behavior separately, but the default mode should be the same for libstdc++ and assert IMO.
    – MSalters
    Mar 25, 2015 at 12:56
  • @MSalters: I can't decide which way I am on that. ATM I think I prefer it opt-in, frankly. Mar 25, 2015 at 13:25
  • @LightnessRacesinOrbit: Do you still want opt-in for debug builds? I'm suggesting opt-in for release builds, opt-out for debug builds.
    – MSalters
    Mar 25, 2015 at 23:09
  • @MSalters: I'd prefer consistency between the two. Mar 26, 2015 at 3:00
1

There are different standard library implementations. Some of them do (msvc 10 for one), some of them not (gcc). The reason not to do it is that it may slow down things tremendously in the debug build to the extent that it is not really usable any more. Usually such implementations still provide some define flag so you can turn it on (-D_GLIBCXX_DEBUG for gcc). On the other side msvc provides _ITERATOR_DEBUG_LEVEL macro to turn it off if you need to.

1
  • Actually this makes sense. I might want a general debug build without turning on core checks that may make my debug build untestable. Mar 25, 2015 at 13:24
-1

I think the reason why assertions on ever case aren't done in standard builds is pretty obvious: they come at a cost, and trying to access something at an index that doesn't exist is a bug in your code, and not in the code of the standard library.

That might be what is different in C and C++ and most higher languages: The desired behaviour is usually more to be consistent with respect to correct calls rather than to be fault-tolerant.

There are reasons not to throw exceptions for a lot of cases, and rather return something that indicates the success of an operation (for example, assume you want to use a find method of a string object -- for performance reasons, and also because "not found" doesn't sound like something unlikely).

foremost, one must realize that throwing an exception is a very complex process, runtime-wise: you initialize a new object of the respective exception, and you start bubbling up the call hierarchy. Often, in cases of catastrophic failure (e.g. programmer did not check whether index is in range), that might even make the whole thing worse (for example, allthough you might assume C++ only runs on "proper" PCs with loads of memory, there's also microcontrollers executing programs written in c++, and a single exception might just eat up all memory).

All in all, C++ just doesn't have your back. It's not your father, teaching how to ride a bike, gently holding you upright if your program starts to slinger. It's rather some guy allowing you to rent a Ferrari: He's not going to teach you how to look over your shoulder when taking a turn, but he's not commenting on your driving style when doing 250 km/h on the autobahn, either. You can do awesome things with that Ferrari, but if you don't take care yourself, you'll have an awesome speed when riding into a wall.

It's not designed to be Java (constantly getting in your way by forcing you to catch exceptions that either just won't occur or are so catastrophic that you'd as well could let your software crash), nor can it afford to be python (not forcing you to do anything, but being a scripting language where the effort of generating an exception object is comparatively normal/small to parsing).

C++ expects you to read your docs, and use caution or the appropriate methods. Many containers have different access methods, some having checks, some not. In many cases, you're already only iterating over indices that are in there (e.g. you do something like for(int i = 0; i < container.length(); i++)), so you don't have to check every time (would just be a waste of time), in some cases you need to do your checking yourself, and in some cases you can use str.at(i), and the library does its checking.

5
  • 1
    All tru, but you're ignoring the fact that we're talking here specifically about debug builds. The programmer has already made it explicit he's not interested in performance.
    – MSalters
    Mar 25, 2015 at 12:58
  • 1
    I know that C++ isn't Java and that it doesn't have my back (not sure Java does have my back, though). I'm just convinced that the "paying for what you use" concept is only applicable in non-debug/non-development builds. .at() always has a runtime cost, even in release builds. I was just trying to understand why standard library programmers decided against using asserts in debug/development builds. You're not expected to get maximum performance in non-release builds, so why not sacrifice a little more performance for safety and productivity while we're at it? Mar 25, 2015 at 13:00
  • Something like that would simply change the behaviour of your code. That's a bad thing in far more cases than you'd think -- I really really want my release code to do the same thing as my debug code. Mar 25, 2015 at 13:04
  • 2
    @MarcusMüller: In what way would it change the behaviour of the code? An assert should fail only when the code is anyway broken. BTW if you think your release code does the same thing as your debug code you're in for a big shock. Why do you think debug code even exists as an independent entity?! Mar 25, 2015 at 13:11
  • 2
    @MarcusMüller: But we're talking about undefined behavior here. You really want your release code to have the same undefined behavior as your debug code? I would be totally happy if undefined behavior occurrences were caught during debug builds testing. Mar 25, 2015 at 13:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.