tartar
tartar

Reputation: 688

Passing Class with a Pointer Member

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

Upvotes: 1

Views: 259

Answers (1)

hochl
hochl

Reputation: 12920

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.

Upvotes: 1

Related Questions