为什么我的调试断言失败?表达式:列表迭代器不可解除引用

时间:2012-12-15 14:16:43

标签: c++ assertions debugging

我在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();
}

**编译和链接成功(0错误/警告)**

但是在运行时我得到了这个错误:

调试断言失败!

程序:exe的路径

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

行:207

Expression:list iterator not dereferenceable

有关程序如何导致断言失败的信息,请参阅有关断言的Visual C ++文档。 (按重试调试应用程序)

1 个答案:

答案 0 :(得分:1)

以下两种错误都是:

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

您的Copy()函数会覆盖从作为第三个参数提供的迭代器开始的元素。因此,目标范围必须有效且足够大以容纳所有要复制的元素。 lcvc都不满足此要求,因此您的代码行为未定义。

修复代码的一种方法是使用std::back_inserter