为什么这段代码会编译

Vic*_*ine 2 c++ eigen

我不明白为什么这段代码编译并运行没有错误:

#include <iostream>
#include <stdio.h>
#include <Eigen/Dense>

int
main (int argc, char *argv[])
{
  typedef Eigen::Matrix<double, 5, 3/*FIXME: Should be 5*/> Matrix5;

  Matrix5 test;
  test << 2,0,0,1,1, 
          0,2,0,1,1,
          0,0,2,2,2,
          0,1,2,0,0,
          0,1,1,0,0; // We filled a 5*5 matrix in a 5*3 matrix

  //std::cout << "Test matrix:\n" << test << std::endl;
  return (0);
}
Run Code Online (Sandbox Code Playgroud)

这是我编译代码的方式:

g++ test_eigen.cpp -o test_eigen -I/usr/include/eigen3 -O3 -DEIGEN_NO_DEBUG
Run Code Online (Sandbox Code Playgroud)

取消注释std::cout,编译,再次运行,您将得到分段错误.我在Ubuntu 14.04上使用Eigen 3.2.0-8.

如建议; 这是Valgrind的输出(带std::cout注释):

$ valgrind ./test_eigen
==12380== Memcheck, a memory error detector
==12380== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==12380== Using Valgrind-3.10.0.SVN and LibVEX; rerun with -h for copyright info
==12380== Command: ./test_eigen
==12380== 
==12380== 
==12380== HEAP SUMMARY:
==12380==     in use at exit: 0 bytes in 0 blocks
==12380==   total heap usage: 0 allocs, 0 frees, 0 bytes allocated
==12380== 
==12380== All heap blocks were freed -- no leaks are possible
==12380== 
==12380== For counts of detected and suppressed errors, rerun with: -v
==12380== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
Run Code Online (Sandbox Code Playgroud)

das*_*ght 5

写过数据结构的分配边界(例如,将5x5矩阵写入分配的5x3)是未定义的行为.它可能会或可能不会崩溃,不幸的是,甚至可能会在没有明显错误的情况下完成.

使用valgrind运行代码以查明与您描述的内存类似的内存问题.