【问题标题】:allocation, deallocation and access of dynamic memory in std::vector [closed]std::vector 中动态内存的分配、解除分配和访问 [关闭]
【发布时间】:2018-03-17 15:27:50
【问题描述】:

以下代码应创建一个图表。为此,有两个类,即边缘和图形。 我们的问题是,程序编译,但崩溃.. 在 Visual Studio 中给出错误,即存在读取访问冲突异常。

我们猜测,这来自指针 e,因为 this 使用错误。但我们不知道到底出了什么问题。

问题:指针是程序崩溃和读取访问冲突异常的原因吗?应该纠正什么?

我们将不胜感激任何帮助和代码更正。

代码:

#include <iostream>
#include <vector>
#include <cassert>

using namespace std;

class edge {
public:
int s,t;
edge(int s, int t) : s(s), t(t) {}
};

class graph {
public:
int m,n;
vector<edge*> *e;
graph(int n, int m) : n(n), m(m) {
    for (int i=0; i<m; i++) {
        (*e).push_back(new edge(i,-1));
    }
}
~graph() {
    for(int i=m-1;i>=0; i--) {
        delete [] (*e)[i];
    }
}

void make_edge(int i, int s, int t) {
    for(i=0;i<m;i++) {
        assert(((*e)[i]->s!=s)&&((*e)[i]->t!=t));
    }
    assert(s!=t);
    assert(s+1==t);

}
};

int main() {
const int n=4;
const int m=3;
graph g(n,m);
g.make_edge(0,0,1);
g.make_edge(1,1,2);
g.make_edge(2,2,3);

return 0;
}

【问题讨论】:

  • 您忘记初始化vector&lt;edge*&gt; *e;。投票结束是错字。
  • 为什么你有一个指向向量的指针而不仅仅是一个向量?我可以想象没有理由指针更可取..
  • 如果你有你的警告,你会看到它
  • 也不要使用std::vector&lt;edge*&gt;,使用std::vector&lt;edge&gt;。这样元素会自动删除,无需手动清理。

标签: c++ pointers graph dynamic-memory-allocation stdvector


【解决方案1】:

您的类graph 正在使用成员e,它是一个指向std::vector&lt;edge*&gt;' 类型的类的指针,但是该成员e 在构造函数中使用之前没有分配。这就是崩溃的原因

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-14
    • 1970-01-01
    • 1970-01-01
    • 2011-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多