views:

183

answers:

3

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:

Myclass::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.

+4  A: 

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.

anon
Didn't know that it was valid to assign to strings like that. +1.
DeadMG
A: 

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

DumbCoder
A: 

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.

Arjit
ACE_Time_Value does not contain strings, and the functions called on it return longs.
anon
Thx for a quick response but could you plz explain your solution a little bit more in details?thx.
Niklas
When the scope of the constructor ends the tm made in constructor also ends. And destructor of tm is called and the end of scope. and to the times is points to also dies. And m_obj lives out of the scope of the constructor so, when the after the constructing of m_obj outside the cons it would point some deleted or de-referenced hence the leak.
Arjit
That is nonsense.
anon
@Neil care to elaborate, or are you just going to let that useless comment hang out there?
Will
@Will See my first comment. And it's not useless, it indicates to the OP that this answerer does not know what he is talking about.
anon