1

I have a simple matrix class which has a 2d integer pointer field in it. When I call following function multiple times, it gives me a glibc error on Linux machine. When I have "otherM.value = '\0';" add this line to the end of function, problem resolves. Could somebody explain me why I have this dangling pointer issue, although class is passed by copy, not by reference? Pointer members are passed by reference?

void matrix::sub(matrix otherM)
{
if(dimX!=otherM.dimX || dimY!=otherM.dimY)
    return;

int** rowPtr = value;   
int** otherMrowPtr = otherM.value;

for(int i=0;i<dimX;i++){
    for(int j=0;j<dimY;j++){                        
        (**rowPtr) = (**rowPtr) - (**otherMrowPtr);
        (*rowPtr)++;
        (*otherMrowPtr)++;
    }
    (*rowPtr)-=dimY;
    (*otherMrowPtr)-=dimY;

    rowPtr++;
    otherMrowPtr++;
}

rowPtr = '\0';
otherMrowPtr = '\0';

otherM.value = '\0';

}

matrix::matrix(int x, int y){

dimX = x;
dimY = y;
// allocate here 
value = new int*[dimX];
int** rowPtr = value;
for(int i=0;i<dimX;i++){
    *rowPtr = new int[dimY];
    rowPtr++;
}
}

matrix::~matrix(){
if(value!=NULL){
    int** rowPtr = value;   
    for(int i=0;i<dimX;i++){
            delete[] (*rowPtr);
            rowPtr++;
    }
    rowPtr-=dimX;
    delete[] rowPtr;
    rowPtr = '\0';
}
value = '\0';
}
tartar
  • 688
  • 4
  • 16
  • How is `value` defined in the class? And why all the pointer arithmetic if you're counting with `i` and `j`? You can just use `rowPtr[i][j]` for much simpler loops. – Adam Liss Mar 16 '12 at 02:19
  • 1
    Did you implement `copy constructor`, `assignment operator` and `destructor` for your class? – hochl Mar 16 '12 at 02:20
  • int** value; is the 2d int pointer which is a data field of matrix class. Just for practice with pointers, I chose working with increments on pointers. I have no copy constructor or assignment operator. – tartar Mar 16 '12 at 02:36
  • Then [go and implement those](http://stackoverflow.com/q/4172722/589206) since you're managing a resource. – hochl Mar 16 '12 at 02:53
  • That's absolutely right. Since when I pass a class without having a proper copy constructor, all pointer fields will be soft-copies. And so, at the end of function scope, local copy of class will be destructed and pointers field will be deallocated once. At the end of the whole program, original class will be destructed but pointers field will have been already deallocated. This is why I received a glibc error. Good to have a copy constructor then. Thank you hochl. – tartar Mar 16 '12 at 03:16
  • I'll add a reply so you can close the question. – hochl Mar 17 '12 at 00:24

1 Answers1

1

Did you implement copy constructor, assignment operator and destructor for your class? If not then go and implement those since you're managing a resource.

Community
  • 1
  • 1
hochl
  • 12,524
  • 10
  • 53
  • 87