使用指针填充向量时出现分段错误

时间:2015-06-18 07:08:25

标签: c++ c++11 vector

我有一个以下形式的课程:

class myClass{
    vector<pair<uint64_t,uint64_t> > myvarClass;
};


main(){
    vector<myClass> myVec;
    myVec.resize(8);
    myClass obj1,obj2,obj3,obj4,obj5,obj6,obj7,obj8;
    myVec.push_back(obj1);myVec.push_back(obj2);myVec.push_back(obj3);
    myVec.push_back(obj4);myVec.push_back(obj5);myVec.push_back(obj6);
    myVec.push_back(obj7);myVec.push_back(obj8);
    myClass* obj1Ptr=&myVec[0]; myClass* obj2Ptr=&myVec[1];
    myClass* obj3Ptr=&myVec[2]; myClass* obj4Ptr=&myVec[3];
    myClass* obj5Ptr=&myVec[4]; myClass* obj6Ptr=&myVec[5];
    myClass* obj7Ptr=&myVec[6]; myClass* obj8Ptr=&myVec[7];
    obj1Ptr->myvarClass.push_back(make_pair(938474,475575));
    //populate myvarClass using obj1Ptr such that the size of myvar for each class object is 4,00,000. I am not showing population of 4,00,000 myvarClass objects for brevity
    //populate myvarClass using obj2Ptr such that the size of myvar for each class object is 4,00,000.  I am not showing population of 4,00,000 myvarClass objects for brevity
    //populate myvarClass using obj3Ptr such that the size of myvar for each class object is 4,00,000.  I am not showing population of 4,00,000 myvarClass objects for brevity
    //populate myvarClass using obj4Ptr such that the size of myvar for each class object is 4,00,000. I am not showing population of 4,00,000 myvarClass objects for brevity
    //populate myvarClass using obj5Ptr such that the size of myvar for each class object is 4,00,000. I am not showing population of 4,00,000 myvarClass objects for brevity
    //populate myvarClass using obj6Ptr such that the size of myvar for each class object is 4,00,000. I am not showing population of 4,00,000 myvarClass objects for brevity
    //populate myvarClass using obj7Ptr such that the size of myvar for each class object is 4,00,000. I am not showing population of 4,00,000 myvarClass objects for brevity
    //populate myvarClass using obj8Ptr such that the size of myvar for each class object is 4,00,000. I am not showing population of 4,00,000 myvarClass objects for brevity
}

当我使用objPtr填充myvarClass时,我最终会在仲裁位置获得分段错误。是否有任何可信的原因。

3 个答案:

答案 0 :(得分:2)

后:

myClass obj1;

然后obj1包含一个未初始化的指针。所以代码:

myVec.push_back(obj1)

按值复制未初始化的变量,这会导致未定义的行为。您的代码中的许多地方都会出现同样的问题。

在行之间阅读,似乎您可能会在未显示的代码中为myPointer提供值,从而导致更多问题。但是,没有人可以调试你没有显示的代码。

答案 1 :(得分:0)

你的问题是,当你从myVec插入指针时,可能会发生myVec调整大小,并且任何指向其内容的指针都会失效。因此你的段错误。

构建向量时的STL保留预定义数量的时隙。如果您插入的元素数量超过此值,则它将保留更多数量的插槽(通常只是将它们加倍)并将旧插槽的内容复制到新插槽中,然后释放旧插槽。这意味着指向旧插槽的指针无效。你可以强制首先保留的插槽数量(有一个专用的构造函数),并克服了这个问题,但通常被认为是依赖于以这种方式获得的指针的不良做法。这样使用std :: vector没有优于数组的优势

答案 2 :(得分:-3)

你的myVec大小为5,你将8个元素压入其中。这可能会导致错误