c++ - boost 多阵列段错误

标签 c++ boost segmentation-fault boost-multi-array

我正在编写一个代码,我使用 3 维 boost 多数组来保存坐标。但我总是在某个时候遇到段错误。 boost 多数组大小如何受到限制以及如何绕过这些限制?

这是重现该问题的简化测试代码:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <string>
#include <algorithm>
#include <map>

#include <boost/multi_array.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
#include "Line.h"

#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>

typedef struct {
    Eigen::Vector3d coords;
    int gpHostZone;
    int gpHostFace;
    int calculated;
} Vertex;


class LGR {
public:
    LGR (int i, int j, int k) :
        grid(boost::extents[i][j][k])
    {
    };

    std::string name;
    std::vector<int> hostZones;
    std::vector<int> refine;
    boost::multi_array<Vertex*, 3> grid;
    std::vector<double> data;
 };

 int main(void){
   LGR lgr(11,11,21);
   std::cout << lgr.grid.size();
   std::vector<LGR> v;
   std::vector<Vertex> vertexDB;
   for(int i = 0; i < 1; i++ ){

     for(int j = 0; j < lgr.grid.size(); j++ ){
       for(int k = 0; k < lgr.grid[0].size(); k++ ){
         for(int l = 0; l < lgr.grid[0][0].size(); l++ ){
           Vertex coord;
           coord.coords << i,j,k;
           coord.gpHostZone = 0;
           coord.gpHostFace = 0;
           coord.calculated = 0;
           vertexDB.push_back(coord);
           lgr.grid[j][k][l] = &(vertexDB.back());
         }
       }
     }

     for(int j = 0; j < lgr.grid.size(); j++ ){
       for(int k = 0; k < lgr.grid[0].size(); k++ ){
         for(int l = 0; l < lgr.grid[0][0].size(); l++ ){
           std::cout << "At ("<< i << ","<< j << ","<< k << "," << l << ")\n";
           std::cout << lgr.grid[j][k][l]->coords<<"\n\n";
         }
       }
     }
   }
   return 1;
 }

请不要对包含内容发表评论。我只是从实际代码中复制并粘贴。其中大部分可能在这里不需要。这些尺寸来自真实的示例,所以我实际上需要这些尺寸(可能还有更多)。

最佳答案

以下是导致未定义行为的明确问题,与 boost::multiarray 没有任何关系.

这些行:

std::vector<Vertex> vertexDB;
//...
vertexDB.push_back(coord);
lgr.grid[j][k][l] = &(vertexDB.back());

调整 vertexDB 的大小 vector ,然后将 vector 中最后一项的指针存储到 lgr.grid[j][k][l] 。这样做的问题是,由于 vector 在调整 vector 大小时必须重新分配内存,因此指向 vector 中项目的指针和迭代器可能会变得无效。

这会在随后的循环中体现出来:

std::cout << lgr.grid[j][k][l]->coords<<"\n\n";

无法保证您之前分配的地址有效。

对此问题的快速解决方法是使用 std::list<Vertex> ,因为将项目添加到 std::list不会使迭代器/指针无效。

关于c++ - boost 多阵列段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39874414/

相关文章:

c++ - lstrcpy在linux中的使用

c++ - 不同上下文中的 QtQuick 动态对象

logging - Boost 1.52.0 上的 Boost.Log 安装错误

c - C 语言的基本更改程序符合要求,但不显示任何输出

c++ - 线程安全的 vector 和字符串容器?

c++ - BST 不添加元素

c++ - Linux,静态库引用可执行文件中的其他静态库

c++ - 使用 istream 从 boost basic_streambuf 读取时出现问题

c++ - Boost Property Tree 是否有为要解析的数据定义规则的方法?

c - 不确定是否为结构分配内存