I need some help to find a memory leak in my C++ code. I try to put these lines in my constructor but it causes a memory leak because of lines 2 and 3 in the constructor:
Myclas开发者_JS百科s::Myclass()
{
ACE_Time_Value tm = ACE_OS::gettimeofday();
m_obj.firstStr() = tm.sec();
m_obj.secondStr() = tm.usec();
}
Here, firstStr()
and secondStr()
are both methods which return std::string&
in another class.
Any suggestion what this memory leak depends on? I'm not sure if these 2 lines are the actual cause of the memory leak but Valgrind points to these two lines and I don't know how to find the leak.
I'm no expert on ACE but it seems unlikely that tm.sec() returns a string - far more likely it returns an integer (in fact it does - it returns a long). In that case, when you call your functions and assign to them you are essentially calling the string's assignment operator which assigns a single character (encoded in the long) to the string. This is almost certainly not what you want, but it should not cause a memory leak.
In other words, you are effectively doing this:
int main() {
string s = "foobar";
cout << s << endl;
s = 65L;
cout << s << endl;
}
which prints:
foobar
A
but does not leak memory.
If you are using any memory leak detectors( and still suspectful) then the next best possible way is to overload your new and delete operator in your debug build and log all your memory allocations and deallocations. One possible help
I think when
ACE_Time_Value tm = ACE_OS::gettimeofday();
is called space string is allocated
and assigned to first and second string But when constructor is done ACE_Time_Value destructor is called which deleted the string allocated.
But they are still referencing to First and second string. Hence the leak.
Trying coping the values. to prevent the leak.
精彩评论