For my home work I need to write String object in C++.
One of the methods is
void concatenate(String *s)
But when I check my object with Valgrind, there is a memory leak in my code. Here is method:
// add s's str to this _str
void String::concatenate(String *s)
{
char * conc;
int conc_size, i, j;
conc_size = _len + s->_len;
conc = new char[conc_size]; // line 39
for (i = 0; i < _len; i++)
conc[i] = _str[i];
for (j = 0; i < conc_size || j < s->_len; i++, j++)
conc[i] = s->_str[j];
_str = conc; // i'm assuming the problem is here
_len = conc_size;
}
Here is Valgrind message:
==4706== 3 bytes in 1 blocks are definitely lost in loss record 2 of 9
==4706== at 0x100024679: malloc (vg_replace_malloc.c:266)
==4706== by 0x10007BF04: operator new(unsigned long) (in /usr/lib/libstdc++.6.0.9.dylib)
==4706== by 0x10007BF96: operator new[](unsigned long) (in /usr/lib/libstdc++.6.0.9.dylib)
==4706== by 0x100000E7E: String::concatenate(String*) (String.cpp:39)
==4706== by 0x100001479: main (main.cpp:27)
Works with delete [] _str; and changed constructors:
// the empty string.
String::String()
{
_len = 1;
_str = new char[_len];
assert(_str);
_str[0] = '\0';
}
// store s string in this
String::String(char *s)
{
_len = 0;
int i = 0;
while(s[i] != '\0')
{
_len++;
i++;
}
_str = new char[_len];
assert(_str);
for (i = 0; s[i] != '\0' && i < _len; i++)
_str[i] = s[i];
}
You’re not dealocating the previous contents of your member
_str. I’m assuming that’s also achar*. So when you’re telling_strto point elsewhere, the memory it previously pointed to will be unacessible.