2

I have been working in a project using matrices and graphs. The problem is when I compile it, the next line pops up:

EXC_BAD_ACCESS (code=2, address=0x7ffff5f3ffff8)

It appears in the next method; which is a constructor of my 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];
}

I have been reading about possible problems and it could be something wrong about pointers:

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

I guess it's something about my pointer pint, but I am new to C++. So, I haven't been able to fix it. By the way0, I'm using Xcode 6.4 on an Intel Macbook Pro.

honk
  • 9,137
  • 11
  • 75
  • 83
  • Calling a constructor within a constructor will not have the apparently expected effect. see this answer for alternatives: http://stackoverflow.com/questions/308276/call-constructor-from-constructor-in-c – kuroi neko Sep 10 '15 at 16:22

1 Answers1

1

As mentioned by @kuroineko in the comments, you cannot call a constructor from another constructor in C++. If you use C++11 (or a later standard) then you can use delegating constructors. Otherwise you might want to define an initialization function, for example, like this:

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];
}

Then you can call this initialization function from your different constructors:

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

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

As far as I can tell, the rest of the shown code should compile. I don't know if the code related to your variable matAd is correct, but at least it doesn't crash for me.

honk
  • 9,137
  • 11
  • 75
  • 83