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

SEG FAULT while assigning memory to the pointer of vector of structs

本文关键字:结构 向量 指针 分配 内存 错误 SEG      更新时间:2023-10-16
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 错误错误......有关将内存分配给结构向量中的指针的任何替代方法的任何建议。

这是因为您正在尝试分配给尚未具有元素的向量。请改为执行以下操作:

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);

循环之前。