對於我的家庭作品,我需要用C++編寫String對象。如何避免我的方法內存泄漏?
其中一種方法是
void concatenate(String *s)
但是,當我檢查我的對象,具有Valgrind的,還有在我的代碼中的內存泄漏。下面是方法:
// 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;
}
這裏是Valgrind的消息:
==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)
工程與delete [] _str;
和改變構造函數:
// 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];
}
你是對的。在給'conc賦值之前,你忘記了'delete [] _str;' – Lol4t0 2012-02-11 19:26:39
誰給作業去實現已經用'std :: string'正確解決的東西? – 2012-02-11 19:26:39
無關的一面注意:不應該在第二個循環的條件是'我 _len'?此外,你爲什麼不使用'std :: copy'? –
reima
2012-02-11 19:30:30