简体   繁体   中英

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.

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. You can set i < someVar which will allow you to decide someVar and the size of the list at runtime.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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