c++ - 将内存分配给结构 vector 指针时出现 SEG FAULT

标签 c++ vector segmentation-fault std

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 错误....关于将内存分配给结构 vector 中的指针的任何替代方法的任何建议。

最佳答案

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

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

虽然这可能是一种更好的方法,因为它可能会更有效率。

关于c++ - 将内存分配给结构 vector 指针时出现 SEG FAULT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13389268/

相关文章:

c++ - 使用指向内部缓冲区的指针 move 语义

c++ - 如何将 vector 内容的 vector 放入单个列 vector 中

c - 段错误回溯到 vfprintf?

c++ - Bison %prec 不起作用

C++ 为什么反转路径是非法的?

c++ - 在 C++ 中使用数组作为条件表达式是否有效?

c++ - 可以安全地使用指向 vector 元素的指针来确定它在容器中的位置吗?

c++ - 为指针 vector 取消引用迭代器时出现段错误

c - 在C中输出文件时出现段错误(核心转储)错误

c++ - 处理删除命令期间出现段错误