簡體   English   中英

提升多陣列分段錯誤

[英]boost multiarray segmentation fault

我正在編寫一個代碼,我使用 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向量的大小,然后將指向向量中最后一項的指針存儲到lgr.grid[j][k][l] 這樣做的問題是,由於在調整向量大小時向量必須重新分配內存,指向向量中項的指針和迭代器可能會失效。

這在后面的循環中表現出來:

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

無法保證您之前分配的地址有效。

對此的快速解決方法是使用std::list<Vertex> ,因為將項目添加到std::list不會使迭代器/指針無效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM