Thursday, December 16, 2010

c++ exceptions and memory leaks

I had to come up with a way to deal with erratic and exceptional condition by C++ exception mechanism.
First I refereed to Google C++ coding convention. They say it is not good to use C++ exception with legacy codes which don't use it.
One of reasons is that it causes resource leaks. see the following code.
Here, h() calls g(), and g() calls f(). The problems is when f() throws an exception, if g() doesn't prepare this situation by RAII or others, a memory is leaked in g().
g() has to be very careful that it cleans up every resources it created in a stack unwinding.

void f() throw(myexception)
{
cout << "f() called" <<>
throw myex;
};

void g()
{
int* leak = new int[10];
cout << "g() called" <<>
f();
delete[] leak;
}

void h()
{
cout << "h() called" <<>
try {
g();
}
catch (exception& e)
{
cout <<>
}
}

valgrind --tool=memcheck --leak-check=yes ./a.out
==11647==
==11647== HEAP SUMMARY:
==11647== in use at exit: 40 bytes in 1 blocks
==11647== total heap usage: 2 allocs, 1 frees, 176 bytes allocated
==11647==
==11647== 40 bytes in 1 blocks are definitely lost in loss record 1 of 1
==11647== at 0x4C27939: operator new[](unsigned long) (vg_replace_malloc.c:305)
==11647== by 0x400DAF: g() (in /home/nhn/workspace/study/c++/exception/a.out)
==11647== by 0x400E15: h() (in /home/nhn/workspace/study/c++/exception/a.out)
==11647== by 0x400E93: main (in /home/nhn/workspace/study/c++/exception/a.out)
==11647==
==11647== LEAK SUMMARY:
==11647== definitely lost: 40 bytes in 1 blocks
==11647== indirectly lost: 0 bytes in 0 blocks
==11647== possibly lost: 0 bytes in 0 blocks
==11647== still reachable: 0 bytes in 0 blocks
==11647== suppressed: 0 bytes in 0 blocks


When you use RAII patterns, there will be no memory leak.

class MyRAII
{
public:
MyRAII()
{
cout << "MyRAII() called" <<> m_data = new int[10];
}

~MyRAII()
{
cout << "~MyRAII() called" <<>
delete[] m_data;
}

private:
int* m_data;
};

void g()
{
int* leak = new int[10];
MyRAII myRaii; // no leak

cout << "g() called" << endl
f();
delete[] leak;
}


http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml?showone=Exceptions#Exceptions
http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr155.htm

0 comments:

Post a Comment