简体   繁体   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
    }

}

I am getting SEG FAULT error for this code while doing the malloc in for loop above....Any suggestions for any alternative to assign memory to the pointer in the vector of structs. 我在上面的for循环中执行malloc时,收到此代码的SEG FAULT错误。...关于将内存分配给结构向量的指针的任何替代方法的任何建议。

It is because you are trying to assign to a vector which does not have the elements yet. 这是因为您试图分配给一个还没有元素的向量。 Do this instead: 改为这样做:

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
 }

That way you will be accessing actual memory. 这样,您将访问实际的内存。

In the comments the OP mentioned that the number of elements in the array will be decided at runtime. OP在评论中提到,数组中元素的数量将在运行时确定。 You can set i < someVar which will allow you to decide someVar and the size of the list at runtime. 您可以设置i < someVar ,这将允许您在运行时确定someVar和列表的大小。

The other answer 另一个答案

leaves.resize(someVar) //before the loop

Is probably a better way to go though because it is likely that it will be more efficient. 不过,这可能是一个更好的方法,因为它可能会更有效率。

You're indexing an empty vector. 您正在索引一个空向量。 Try using 尝试使用

leaves.resize(100);

Before the loop. 循环之前。

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

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