Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behavior when dereferencing the .end() of a vector of strings

Tags:

c++

I'm wondering if it's "safe" to set a string equal to whatever is returned by dereferencing the off-the-end iterator of a vector of strings. When I run the program

#include <vector>
#include <string>

int main()
{

    std::vector<std::string> myVec;
    std::cout << *myVec.end();
    return 0;
}

I get the following error.

/usr/local/lib/gcc/i686-pc-linux-gnu/4.1.2/../../../../include/c++/4.1.2/debug/safe_iterator.h:181:
    error: attempt to dereference a past-the-end iterator.

Objects involved in the operation:
iterator "this" @ 0x0xffdb6088 {
type = N11__gnu_debug14_Safe_iteratorIN9__gnu_cxx17__normal_iteratorIPSsN10__gnu_norm6vectorISsSaISsEEEEEN15__gnu_debug_def6vectorISsS6_EEEE (mutable iterator);
  state = past-the-end;
  references sequence with type `N15__gnu_debug_def6vectorISsSaISsEEE' @ 0x0xffdb6088
}

Disallowed system call: SYS_kill

You can view it at http://codepad.org/fJA2yM30

The reason I'm wondering about all this is because I have a snippet in my code that is like

std::vector<const std::string>::iterator iter(substrings.begin()), offend(substrings.end());
while (true)
{
    this_string = *iter;
    if (_programParams.count(this_string) > 0)
    {
        this_string = *++iter;

and I want to make sure something weird doesn't happen if ++iter is equal to offend.

like image 826
Failed Software Developer Avatar asked Nov 17 '14 04:11

Failed Software Developer


1 Answers

You said:

I'm wondering if it's "safe" to set a string equal to whatever is returned by dereferencing the off-the-end iterator of a vector of strings

No, it is not safe. From http://en.cppreference.com/w/cpp/container/vector/end

Returns an iterator to the element following the last element of the container.

This element acts as a placeholder; attempting to access it results in undefined behavior.

like image 147
R Sahu Avatar answered Oct 26 '22 05:10

R Sahu