0

I'm currenty writing small application for image processing. However I have a big problem with memory usage of my program. I'm fairy new in c++, previously I mainly was programing in c#.

The function which do almost all the work looks like that

while(!prototypeVector[i]->GetIsConvergaed()) 
{
    if(previousPrototype!=NULL) delete previousPrototype;
    previousPrototype = prototypeVector[i]->CopyPrototype();

    if(&matchingPointVector!=NULL) matchingPointVector.clear();
    matchingPointVector = prototypeVector[i]->CalculateMatchingPointsAll(imageDataVector); 
    distanseMatrix = CalculateDistanceAll(i);

    membershipMatrix = UpdateMembershipAll(i);

    if(translation)
    {
        tmatrix = UpdateTranslationMatrix(i);
        if(directUpdate) prototypeVector[i]->SetTranslationMatrix( tmatrix);

        //prototypeVector[i]->GetTranslationMatrix().DisplayMatrix();
        tmatrix.DisplayMatrix();
    }
    if(scaling)
    {
        smatrix = UpdateScalingMatrix(i);
        if(directUpdate) prototypeVector[i]->SetScalingMatrix(smatrix);
        smatrix.DisplayMatrix();
    }
    if(rotation)
    { 
        angle =  UpdateAngleCoefficient(i);
        cout<<endl;
        Convert::RadiansToDegrees(angle)<<endl;
        if(directUpdate)prototypeVector[i]->UpdateRotationMatrix(angle);
    }

    prototypeVector[i]->TransformTemplateOne(prototypeVector[i]->GetRotationMatrix(), prototypeVector[i]->GetScalingMatrix()  , prototypeVector[i]->GetTranslationMatrix());
}

I noticed that if in function written above is called another function

CalculateMatchingPointsAll or CalculateDistanceAll or UpdateScalingMatrix the memory usage rises dramatically about (300kB after execution each of functions mentioned above). So I suppose the problem is in these functions. They look like that

vector<Point*> TemplateClusterPoint::CalculateMatchingPointsAll( vector<Point*> imageDataVector)
{
    vector<Point*> matchinPointVector = vector<Point*>(imageDataVector.size(),new Point(0,0));
    double minValue = DOUBLE_MAX_VALUE;
    double currentDistance = 0;
    for (int i=0;i<imageDataVector.size();i++ )
    {
        //matchinPointVector[i] = this->CalculateMatchingPoint(/*prototypePointVector,*/imageDataVector[i]);
        for (int j=0;j<prototypePointVector.size();j++)
        {
            if( (currentDistance = CalculateDistance(imageDataVector[i],prototypePointVector[j]) ) <= minValue )
            {

                minValue = currentDistance;
                matchinPointVector[i] = prototypePointVector[j];
            }
        }
        minValue =   currentDistance = DOUBLE_MAX_VALUE;
    }
    return matchinPointVector;
}


vector<vector<double>> AlgorithmPointBased::CalculateDistanceAll( int clusterIndex)
{
    //vector<Point*> pointVector = prototypeVector[clusterIndex]->GetPrototypePointVector();
    Point* firstPoint = NULL;
    Point* secondPoint = NULL;
    for(int i=0;i<imageDataVector.size();i++ )
    {
        firstPoint = imageDataVector[i];
        secondPoint = matchingPointVector[i];

        distanseMatrix[clusterIndex][i] =  pow( (firstPoint->GetX() - secondPoint->GetX() ), 2    ) + pow( (firstPoint->GetY() - secondPoint->GetY() ), 2);   //(difference*difference)[0][0]; //funkcja dystansu = d^2 = (Xi - Pji)^2
                                                                                    // gdzie Xi punkt z obrazu, Pij matching point w danym klastrze
    }
    return distanseMatrix;
}

Matrix<double> AlgorithmPointBased::UpdateScalingMatrix( int clusterIndex )
{

    double currentPower = 0;
    vector<Point*> prototypePointVecotr = prototypeVector[clusterIndex]->GetPrototypePointVector();
    vector<Point*> templatePointVector = templateCluster->GetTemplatePointVector();
    Point outcomePoint;
    Matrix<double> numerator =  Matrix<double>(1,1,0);
    double denominator=0;
    for (int i=0;i< imageDataVector.size();i++)
    {
        Point templatePoint =  *matchingPointVector[i]; 
         currentPower = pow(membershipMatrix[clusterIndex][i],m);
        numerator += /  ((*imageDataVector[i] - prototypeVector[clusterIndex]->GetTranslationMatrix()).Transpose()* (prototypeVector[clusterIndex]->GetRotationMatrix() * templatePoint )* currentPower);
        denominator += (currentPower* (pow(templatePoint.GetX(),2) +  pow(templatePoint.GetY(),2)));   
    }
     numerator /= denominator;
    return numerator;
}

As You can see almost all the work these function do is calculating new points or closest point or transormating an image. Is there any way to somehow release at least some memory after these functionos were executed. I suppose that the most memory consuming operations are multiplication of matrices or operations on points. I have overloaded operator + * and / which of course return new objects.

EDITED Overloaded operators look like that

Point Point::operator*( double varValue )
{
    return *(new Point(this->x * varValue,this->y * varValue));
}

Point Point::operator-( Point& secondPoint )
{
    return *(new Point(this->x - secondPoint.GetX(),this->y - secondPoint.GetY()));
}

Point Point::operator*( double varValue )
{
    return *(new Point(this->x * varValue,this->y * varValue));
}

template<typename T>
Matrix<T> Matrix<T>::operator + (double value)
{
    Matrix<T>* addedMatrix = new Matrix<T>(this->rows,this->columns);
    for (int i=0;i<this->rows;i++)
    {
        for (int j=0;j<this->columns;j++)
        {
            (*addedMatrix)[i][j] = (*this)[i][j]+ value;
        }
    }
    return *addedMatrix;
}

Point Point::operator/( double varValue )
{
    return *(new Point(this->x / varValue,this->y / varValue));
}
3
  • "I have overloaded operator + * and / which of course return new objects." What do those functions look like? Mar 30, 2011 at 22:53
  • 2
    If you are learning C++, make sure that you have a good introductory book. C# and C++ are very different languages. Mar 30, 2011 at 23:05
  • @James McNellis take a look at my edit
    – elNinio
    Mar 30, 2011 at 23:11

2 Answers 2

10

I'm fairy new in C++, previously I mainly was programing in C#.

Unlike C#, C++ has no garbage collection. Any time that you use new (e.g., new Point(0,0)), you are responsible for using delete to destroy that object.

Ideally, you should avoid dynamically allocating objects explicitly and eschew new and delete altogether. You should prefer to create objects with automatic storage duration (on the stack) and work with copies of them (by passing them by value or reference, returning them by value, and storing copies of them in containers).

Among other things, you should almost certainly be using a std::vector<Point> instead of a std::vector<Point*>.


return *(new Point(this->x * varValue,this->y * varValue)); 

All of your functions that have code like this are wrong: you dynamically allocate an object, return a copy of that object, and lose all references to the original. You are left without any way to destroy the dynamically allocated object. You don't need to dynamically allocate anything here. The following would suffice:

return Point(x * varValue, y * varValue);

if(&matchingPointVector!=NULL)

This can never be false in a correct program: & takes the address of an object and no object can have the address NULL. The only way this could happen is if you had already dereferenced a null pointer somewhere in your program, in which case you're already in a heap of trouble.


Make sure that you have a good introductory C++ book. C++ and C# are very different programming languages.

3
  • Uhm, don't you mean pass objects around by reference? Mar 30, 2011 at 22:59
  • Talking about memory management, I'd mention also smart pointers. Mar 30, 2011 at 23:04
  • Thanks for answer, I have a couple more question though. You wrote that You wrote "Ideally, you should avoid dynamically allocating objects explicitly and eschew new and delete altogether" so what is the point of existing pointers in c++. What is an advantage of using them ??
    – elNinio
    Mar 31, 2011 at 16:45
0

C++ is a non managed language meaning you have to manage the memory yourself(as James said). When you create a variable like this e.g: int i = 3; the variable is created on the system stack and only exists until it falls out of scope (the end of the curly braces "}" ) meaning you don't have to manage the memory for them. However if you create a variable like this int *ia_array = new int [5]; you have created a pointer (to which could point to anything of the same type and can change what its pointing to, that also doesn't fall out of scope) and then create the array on the heap, to which the pointer is pointing to. Therefore you have to delete the array it self off the heap and the pointer that points to it. id recommend reading this Cplusplus.com tutorial on dynamic memory. Also have a look at this very good youtubevideo on how to correctly manage the dynamically allocated memory. Finally you might want to look up "smart pointers" for if you end up using a lot of pointers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.