SEG FAULT,同时将内存分配给结构向量的指针

ASi*_*ngh 1 c++ vector std segmentation-fault

struct LeafDataEntry   
{
    void *key;
    int a;
};


int main(){

    //I want to declare a vector of structure
    vector<LeafDataEntry> leaves;

    for(int i=0; i<100; i++){
       leaves[i].key = (void *)malloc(sizeof(unsigned));
       //assign some value to leaves[i].key using memcpy
    }

}
Run Code Online (Sandbox Code Playgroud)

我在上面的for循环中执行malloc的时候得到了这个代码的SEG FAULT错误....任何建议任何替代方案都可以在结构向量中为指针分配内存.

Fan*_*Fox 5

这是因为您正在尝试分配给尚未包含元素的向量.改为:

for(int i=0; i<100; i++){
    LeafDataEntry temp;
    leaves.push_back(temp); 
    leaves[i].key = (void *)malloc(sizeof(unsigned));
    //assign some value to leaves[i].key using memcpy
 }
Run Code Online (Sandbox Code Playgroud)

这样你就可以访问实际的内存了.

在评论中,OP提到数组中的元素数量将在运行时决定.您可以设置i < someVar允许您someVar在运行时决定列表大小的内容.

另一个答案

leaves.resize(someVar) //before the loop
Run Code Online (Sandbox Code Playgroud)

可能是一种更好的方式,因为它可能会更有效率.