繁体   English   中英

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

[英]SEG FAULT while assigning memory to the pointer of vector of structs

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
    }

}

我在上面的for循环中执行malloc时,收到此代码的SEG FAULT错误。...关于将内存分配给结构向量的指针的任何替代方法的任何建议。

这是因为您试图分配给一个还没有元素的向量。 改为这样做:

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
 }

这样,您将访问实际的内存。

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

另一个答案

leaves.resize(someVar) //before the loop

不过,这可能是一个更好的方法,因为它可能会更有效率。

您正在索引一个空向量。 尝试使用

leaves.resize(100);

循环之前。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM