IBM Support

Memory leaks when using STL container classes implemented by the GNU C++ library

Troubleshooting


Problem

In this situation IBM® Rational® Test RealTime® reports a memory leak. This happens when you use the Standard Template Library (STL) container classes, vector, list, and others, implemented in the GNU C++ library. You see this even though the code destroys the container object at the end of the function. Consider the following example code. [] #include #include #include using namespace std; main() { vector v(6); /*[] MLK : Memory leaked here []*/ for (int j=0; j<6; j++) { v[j] = j; cout << j << ": " << v[j] << endl; } v.clear(); } [] Test RealTime reports a memory leak at the declaration of []v[] even though the code destroys it at the end of the function.

Cause

This occurs because of the way the GNU C++ runtime library has implemented these classes. On these templates there is a second template parameter, that has a default value of

__default_alloc_template .

This class handles the memory allocation from within the template class. The default template uses a memory cache to reduce the number of calls to malloc() and free(). Therefore, in the preceding example the template calls malloc() to allocate the memory for the variable v. When this variable is destroyed, template class puts the memory into the cache ready for re-use. This means that there is no call to free(). As a consequence Test RealTime considers this as a memory leak.

Resolving The Problem

There is no real solution to this without modifying the code under test. It is possible to force the STL template classes to always call malloc() and free(). You can specify another memory allocation template as the second template parameter to the template type.

Example :


#include<list>
#include<vector>
#include<iostream>

using namespace std;

main()
{
vector<int, __malloc_alloc_template<0> > v(6);
for (int j=0; j<6; j++) {
v[j] = j;
cout << j << ": " << v[j] << endl;
}
v.clear();
}



Now Test RealTime will not report a memory leak. The template classes will call free() when the variable v goes out of scope.




[{"Product":{"code":"SSSHUF","label":"Rational Test RealTime"},"Business Unit":{"code":"BU053","label":"Cloud & Data Platform"},"Component":"Not Applicable","Platform":[{"code":"PF002","label":"AIX"},{"code":"PF010","label":"HP-UX"},{"code":"PF016","label":"Linux"},{"code":"PF027","label":"Solaris"}],"Version":"2002.05.00;2002.05.20;2003.06.00;2003.06.01;2003.06.12;2003.06.13;2003.06.15;7.0;7.0.0.1","Edition":"","Line of Business":{"code":"LOB45","label":"Automation"}}]

Document Information

Modified date:
16 June 2018

UID

swg21160634