I have a weird problem with destructors. My code works in older machines with g++-2.95, g++-3.3, g++-4.0, g++-4.0.1 and not in my machine with g++-4.4.1. Do you know why? Here I show a small example that reproduces the error (in my machine):

#include <iostream>
class Matrix{
  public:
    Matrix(){};
    Matrix(int nin);
    ~Matrix();
    int Set();
  private:
    int n;
    double * data;
};

Matrix::Matrix(int nin){
  n = nin;
  data = new double[n];
  std::cout << "Constructor  " << data << std::endl;
}
Matrix::~Matrix(){
  std::cout << "Destructor  " << data << std::endl;
  delete [] data; data = NULL;
  std::cout << "End destructor  " << data << std::endl;
}
int Matrix::Set(){
  for (int i=0;i<n;i++){
    data[i*n+i] = 1.;
  }
}


int main(){
  Matrix A(50);
  A.Set();
  std::cout << "Finished normally" << std::endl;
}

Thanks in advance

> data[i*n+i] = 1.;
Well this would appear to walk MASSIVELY off the end of the allocated space.

You need to allocated n*n for a square matrix.

I have a weird problem with destructors. My code works in older machines with g++-2.95, g++-3.3, g++-4.0, g++-4.0.1 and not in my machine with g++-4.4.1. Do you know why? Here I show a small example that reproduces the error (in my machine):

#include <iostream>
class Matrix{
  public:
    Matrix(){};
    Matrix(int nin);
    ~Matrix();
    int Set();
  private:
    int n;
    double * data;
};

Matrix::Matrix(int nin){
  n = nin;
  data = new double[n];
  std::cout << "Constructor  " << data << std::endl;
}
Matrix::~Matrix(){
  std::cout << "Destructor  " << data << std::endl;
  delete [] data; data = NULL;
  std::cout << "End destructor  " << data << std::endl;
}
int Matrix::Set(){
  for (int i=0;i<n;i++){
    data[i*n+i] = 1.;
  }
}


int main(){
  Matrix A(50);
  A.Set();
  std::cout << "Finished normally" << std::endl;
}

Thanks in advance

Well, to start, your set function is wild!

for (int i=0;i<n;i++){
    data[[B]i*n+i[/B]] = 1.;
  }

Suppose your matrix was initialized with 50 elements. At the 38th iteration of your loop, you would be trying to access the 1938th element of the array. This obviously should break something, and that's probably where you're getting a "double free or corruption." I don't understand why you aren't accessing your items like this:

for (int i=0;i<n;i++){
    data[[B]i[/B]] = 1.0;
  }
}

Try to fix that first, and then see what happens.

You are right. I wrote my classes too qucikly and I haven't saw the error. I tried to reproduced a segmentation fault of a bigger code and I haven't realised the "typo". In the "big" code it is properly set the size of the array. So I keep on searching...

Thanks and sorry

This question has already been answered. Start a new discussion instead.