0

Here's my structure:

struct animal
{
    int position;
    int** shape;
    int rows, cols;
    int force;
    int minSafety;
    void init(int r,int c,int k, int t, int p)
    {
        shape = new int*[r];
        for(int i = 0; i < r; i++)
        {
            shape[i] = new int[c];
        }
        rows = r;
        cols = c;
        force = k;
        minSafety = t;
        position = p;
    }
    ~animal()
    {
        for(int i = 0; i < rows; i++)
        {
            delete[] shape[i];
        }
        delete[] shape;
    }
};

I have an array of such structures and I want to sort that array in ascending order by the "force". Here's my array and the predicate function I use to pass to the "sort" function from the STL.

bool sortByForce(animal& animal1, animal& animal2)
{
    return animal1.force !=  animal2.force ?
        animal1.force < animal2.force : animal1.rows * animal1.cols > animal2.rows * animal2.cols;
}
animal* animals = new animal[P];
//sort(animals, animals+P, &sortByForce);

When I uncomment the sort function the code breaks. I think it's because of the dynamic arrays inside the structures. (It actually sorts the array but the "shape" arrays are broken iside the structures.) Thanks :)

3
  • 1
    Did you try to debug it and see where it fails ? Commented Oct 22, 2012 at 9:26
  • ^ - Likewise, the code in which you use these functions as well (like your main). Commented Oct 22, 2012 at 9:27
  • 1
    @jogoapan oh I missed that. edited my comment :) Commented Oct 22, 2012 at 9:29

1 Answer 1

2

Your destructor is being called on temporary objects:

animal a;
a.init(...);
{
    animal tmp = a;
} // tmp destructor called, frees memory belonging to a

You need to respect the Rule of Five, either by writing a copy constructor, move constructor, copy assignment operator and move assignment operator, or by replacing shape with a managed container e.g. std::vector<std::vector<int>>.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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