尝试访问向量中的对象中的字段时的Segfault

时间:2014-10-15 05:30:30

标签: c++ vector segmentation-fault

这似乎是最直接的事情,但无论我尝试什么,它都能保持分段。对不起,如果它显而易见且易于搜索,我一直在搜索无数向量段错误线程大约2个小时,似乎没有人有这个确切的问题。

class A
{
protected:
    std::vector<B> myVector = std::vector<B>(1);
    void doStuff();
};

void A::doStuff()
{
    myVector.push_back(B());
    myVector[0].initiate();
}

class B
{
public:
    int a;
    B();
    void initiate();
};

B::B()
{
}

void B ::initiate()
{
    a = 0; //**this is where segfault happens**
}

另外,如果我在B中放置一个矢量怎么办?每当我使其中一个组件具有更大的内部向量时,Bs的向量是否必须完全重新分配?或者那段错误呢?在任何一种情况下,有没有办法为每个向量槽分配一个固定数量的内存或什么东西,我希望增长的对象???

编辑: “A” 的.h

#ifndef PLATE_H
#define PLATE_H

#include "Column.h"
#include <vector>

class World;
class Plate
{
protected:
    World* myWorld;
    std::vector<Column> vColumns = std::vector<Column>(1); 

“A” 的.cpp:

void Plate::initiate(unsigned short xDim, unsigned short yDim, World * world)
{
    myWorld = world;
    dMass = 0;

    for (int x = 0; x < xDim; x++) {
        for (int y = 0; y < yDim; y++) {
            vColumns.push_back(Column());
            std::cout << vColumns.size();
            vColumns[x + y*xDim].initiate(5,myWorld->cMantleDensity,myWorld); //%%%%%%% 5 is temporary
            dMass = dMass + vColumns[x + y*xDim].getDensity() * vColumns[x + y*xDim].getNumGoxels();
        }
    }
}

“B” 的.h:

#ifndef COLUMN_H
#define COLUMN_H
#include <vector>
#include "Goxel.h"

class World;
class Column
{
protected:
    World* myWorld;
    std::vector<Goxel> vGoxels;
    unsigned char cCrumple;
    unsigned char cVolcanism;
    unsigned short sThickness;
    short sRootDepth;
    float fDensity;
public:
    Column();
    void initiate(unsigned short, unsigned char,World* const);

“B” 的.cpp:

void Column::initiate(unsigned short thick, unsigned char mantleDensity,World* world)
{
    myWorld = world;
    cCrumple = 0;
    cVolcanism = 0;
    sThickness = thick;
    fDensity = 58; //basalt
    sRootDepth = (short)(-((sThickness * fDensity) / mantleDensity));

    for (int i = 0; i < thick; i++)
    {
        vGoxels.push_back(Goxel());
        vGoxels[i].quickInitiate((char)(((i-1)*58) / 20));
    }
}

1 个答案:

答案 0 :(得分:0)

这样做:

$ gdb a.out
> run
*segfault*
> where

调试器将向您显示段错误实际所在的堆栈跟踪,以便您不必猜测。