c++ - 为什么我得到这个调试断言失败?表达式 : list iterator not dereferenceable

标签 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路径

文件:\program files\ms vs studio 10.0\vc\include\list

行:207

表达式:列表迭代器不可取消引用

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

最佳答案

以下两种错误:

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 .

关于c++ - 为什么我得到这个调试断言失败?表达式 : list iterator not dereferenceable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13893237/

相关文章:

debugging - Visual Studio 远程调试服务

debugging - 如何跟踪重复分配的生命周期堆使用情况

c++ - 从地址查找堆或堆 block 或段

nunit - AreEqual 与 ToString 比较对象

unit-testing - 如何在R中进行断言?

c++ - static_assert 无法检查模板化对象指针

python - 为什么 PTVS 这么慢?

c++ - 从 ostringstream 传递到 istringstream 的技巧

c++ - 如何在编译过程中编辑可执行文件而不更改其源代码?

c++ - atomic.store 和atomic_thread_fence 有什么区别?