Karel
Karel

Reputation: 508

Why do I get this Debug Assertion Failed? Expression: list iterator not dereferenceable

I'm trying this example in the (translated to dutch) book of Bjarne Stroustrup (C++):

#include <vector>
#include <list>
#include "complex.h"

complex ac[200];
std::vector<complex> vc;
std::list<complex> l;

template<class In, class Out> void Copy(In from, In too_far, Out to) {
    while(from != too_far) { 
            *to = *from;
            ++to;
            ++from;
            }
}

void g(std::vector<complex>& vc , std::list<complex>& lc) {
    Copy(&ac[0], &ac[200], lc.begin());           // generates debug error
    Copy(lc.begin(), lc.end(), vc.begin());       // also generates debug error
}

void f() {
    ac[0] = complex(10,20);
    g(vc, l);
}

int main () {
    f();
}

** Compiling and Linking goes successful (0 errors/warnings)**

But at runtime I get this error:

Debug Assertion Failed!

Program: path to exe

file: \program files\ms vs studio 10.0\vc\include\list

Line: 207

Expression: list iterator not dereferenceable

For information on how your program can cause an assertion failure, see the Visual C++ documentation on asserts. (Press retry to debug the application)

Upvotes: 2

Views: 1890

Answers (1)

NPE
NPE

Reputation: 500317

Both of the following erroneous:

Copy(&ac[0], &ac[200], lc.begin());           // generates debug error
Copy(lc.begin(), lc.end(), vc.begin());       // also generates debug error

Your Copy() function overwrites elements starting at the iterator supplied as the third argument. Therefore, the destination range has to be valid and large enough to accommodate all the elements being copied. Neither lc nor vc satisfy this, so the behaviour of your code is undefined.

One way to fix your code is by using std::back_inserter.

Upvotes: 1

Related Questions