glibc detected: double free or corruption

C

chuan

I define a class with a private dynamical member

Class A
{
double *data;
public:
A();
~A();
}

In constructor I assign a block memory to data,

A::A(){
data = new double [size];
}

and delete it in the desturctor

A::~A(){
delete [] data;
}

So far so good, but when I trying to overload some arithmetic operator
(+ or /),
I receive the "glibc detected: double free or corruption" error. Here
is my code

A A::eek:perator+(A add){
A tmp;
for (int i=0; i<size; i++)
tmp = this->data + add.data;
return tmp;
}

Please give me a hint.
 
S

Salt_Peter

I define a class with a private dynamical member

Class A
{
  double *data;
public:
  A();
  ~A();

}
;


In constructor I assign a block memory to data,

A::A(){
  data = new double [size];

}

What is size?
and delete it in the desturctor

A::~A(){
  delete [] data;

}

So far so good, but when I trying to overload some arithmetic operator
(+ or /),
I receive the "glibc detected: double free or corruption" error. Here
is my code

A A::eek:perator+(A add){
  A tmp;
  for (int i=0; i<size; i++)
         tmp = this->data + add.data;
  return tmp;


Passing by value and returning a copy by value. Bad news. Think member
data (which is a pointer). Rename member to p_data and you'll get it.
}

Please give me a hint.

don't use pointers, pass by reference to constant and use dynamic
containers.
 
J

James Kanze

chuan said:
I define a class with a private dynamical member
Class A
{
 double *data;
public:
 A();
 ~A();
}
In constructor I assign a block memory to data,
A::A(){
 data = new double [size];
}
and delete it in the desturctor
A::~A(){
 delete [] data;
}
So far so good, but when I trying to overload some
arithmetic operator (+ or /), I receive the "glibc detected:
double free or corruption" error. Here is my code
A A::eek:perator+(A add){
 A tmp;
 for (int i=0; i<size; i++)
        tmp = this->data + add.data;
 return tmp;
}
Please give me a hint.

Google "the rule of three c++" (without quotes, of course).

Actually, putting the quotes around "rule of three" might not be
a bad idea.

More generally, of course, I'd ask why he was using new[] and
delete[] to begin with. They're almost always a sign of bad
implementation; in this case, I fail to see why
std::vector<double> wouldn't do the job, much better.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,149
Members
46,695
Latest member
StanleyDri

Latest Threads

Top