Exc_bad_access 有指针

Exc_bad_access with pointers

我一直在一个使用矩阵和图形的项目中工作。问题是当我编译它时,弹出下一行:

EXC_BAD_ACCESS (code=2, address=0x7ffff5f3ffff8)

出现在下一个方法中;这是我的 class:

的构造函数
GrafoMatriz::GrafoMatriz(){
    maxVerts = 1;
    GrafoMatriz(maxVerts);
}
typedef int * pint;

class GrafoMatriz {
    ...
    int maxVerts;
    int numVerts; 
    Vertice * verts; // there's another class Vertice
    int ** matAd; 

    GrafoMatriz();
    GrafoMatriz(int mx); 
    ...
}

GrafoMatriz::GrafoMatriz (int mx){
    maxVerts = mx;
    verts = new Vertice[mx]; 
    matAd = new pint[mx]; 
    numVerts = 0;
    for (int i = 0; i < mx; i++)
        matAd[i] = new int[mx];
}

我一直在阅读可能的问题,指针可能有问题:

The pointer could have never been initialized.

The pointer could have been accidentally written over because you overstepped the bounds of an array.

The pointer could be part of an object that was casted incorrectly, and then written to.

Any of the above could have corrupted a different pointer that now points at or near this pointer, and using that one corrupts this one (and so on).

我想这与我的指针有关 pint,但我是 C++ 的新手。所以,我无法修复它。顺便说一句,我在 Intel Macbook Pro 上使用 Xcode 6.4。

正如@kuroineko 在评论中提到的,您不能在 C++ 中从另一个构造函数调用构造函数。如果你使用C++11 (or a later standard) then you can use delegating constructors。否则你可能想要定义一个初始化函数,例如,像这样:

void GrafoMatriz::Initialize(int mx){
    maxVerts = mx;
    verts = new Vertice[mx];
    matAd = new pint[mx];
    numVerts = 0;
    for (int i = 0; i < mx; i++)
        matAd[i] = new int[mx];
}

然后你可以从不同的构造函数中调用这个初始化函数:

GrafoMatriz::GrafoMatriz(){
    Initialize(1);
}

GrafoMatriz::GrafoMatriz (int mx){
    Initialize(mx);
}

据我所知,所示代码的其余部分应该可以编译。我不知道与您的变量 matAd 相关的代码是否正确,但至少它不会对我造成崩溃。