Memory Management : character arrays and = operator


Memory Management : character arrays and = operator

Q. In terms of Memory Management, What error would you have with the following code?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class String
{
public:
 String(const char right[]);
 String& operator= (const String& right);
 int length() const;
private:
 char* buffer;
 int len;
};

int String::lenght() const {return len;}

String::String(const char right[])
{
  len = 0;
  while (right[len] != '\0')
    len++;
  buffer = new char[len+1];
  for (int i = 0; i < len; i++)
    buffer[i] = right[i];
  buffer[len] = '\0';
}

String& String::operator= (const String& right)
{
  int n = right.length();
  for (int i = 0; i <= n; i++)
    buffer[i] = right.buffer[i];
  return *this;
}


Answer.
I have no clue... Could you help me?
The array size seems okay... new operator...
is it because of the dangling pointer because there is no delete operator?

Please let me know.
Thanks,
You're right about the delete issue; there ought to be a destructor that handles that. I also noticed that in the operator equals we don't re-allocate memory for buffer so it may not be long enough to hold the entire contents of the String right.
What if: this == &right
Topic archived. No new replies allowed.