glibc detected

I have been trying for hours to figure out why I get this error, or how to fix it. The class seems very simple, but I cannot figure this out. Any help is appreciated.
1
2
3
4
5
6
7
8
9
10
11
12
13
String& String::operator=( const String& A )
{
   this->Capacity = A.Capacity;
   this->Length = A.Length;

   this->Mem = new char[Capacity];

    for ( unsigned I=0; I<this->Length; I++ )
   {
      this->Mem[I] = A[I];
   }
   return *this;
}


This is the program I am using it with...
1
2
3
4
5
6
7
8
int main()
{
   String A("HELLO!");
   String B = A;

   cout << A << endl;
   cout << B << endl;
}


The program outputs this....
1
2
3
4
HELLO!

*** glibc detected *** free(): invalid pointer: 0xf7f11ff4 ***
Abort

The problem is probably in your constructor/destructor. Please post those.
Here's the constructor...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
String::String( const char A[] )
{
   char X = A[0];
   int pos = 0;
   Length = 0;

   while (X!='\0')
   {
      Length++;
      pos++;
      X = A[pos];
   }
   Capacity = 16;
   while (Length > Capacity)
   {
      Capacity+=16;
   }
   Mem = new char[Capacity];
   for (unsigned I=0; I<Length; I++)
   {
      Mem[I] = A[I];
   }
}


Here's the destructor...

1
2
3
4
5
6
7
String::~String()
{
   Length = 0;
   Capacity = 0;
   delete [] Mem;
   Mem = NULL;
}
The error is because your String class is attempting to delete[] the Mem array more than once.

Have you written a proper copy constructor for the class?

[edit] Argh, wait a moment before posting and miss the conversation...
Last edited on
No I haven't written the copy constructor. I was told to start with the constructor then move down and this is the next class function. Should I consider attempting the copy constructor?
Yes, you need a copy constructor (and it needs to work like operator=)

In general, if you have to write operator=, you also need a copy constructor and vice versa.

You should note that your operator= is not called by line 4 of your main even though you use the assignment operator. In reality the compiler is invoking the copy constructor.

Thanks for the help i made the copy constructor the same without the return *this; and everything worked fine...


Thanks everyone... i will probably have more questions on here later..
Topic archived. No new replies allowed.