简体   繁体   中英

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)

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM