使用向量的C ++中的分段故障 [英] Segmentation fault in C++ using vectors

查看:122
本文介绍了使用向量的C ++中的分段故障的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到由以下行引起的细分错误的问题:

I'm having trouble with a segmentation fault caused by the following line:

heapVec[currentsize] = *(new Node(d));

我在这里做错了什么?

#include <vector>
using namespace std;

class Node {
private:
    int data;
public:
    Node(int);
    // ~Node();
};

class Heap {
private:
    vector<Node> heapVec;
    int currentsize;
public:
    Heap();
    // ~Heap();
    void insert(int);
    void extractMin();
    void reduceKey();
};

Node::Node(int d) {
    data = d;
}

void Heap::insert(int d) {
    heapVec[currentsize] = *(new Node(d));
    currentsize++;
}

Heap::Heap() {
    // this is the default constructor
    currentsize = 0;
}

int main() {
    Heap *h = new Heap;
    h->insert(10);
}


推荐答案

当您使用下标运算符写出其边界时自动。要插入到向量的末尾(增加它的大小)使用:

A vector doesn't grow automatically when you write out of its bounds using subscript operator. To insert to the end of the vector (increasing its size) use this:

heapVec.push_back(Node(d));

也不要使用 *(new Node(d) code>,它不会segfault,但它的内存泄漏。

Also don't use *(new Node(d)), it won't segfault, but its a memory leak.

这篇关于使用向量的C ++中的分段故障的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆