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
]
Test RealTime reports a memory leak at the declaration of [
#include
]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.
Was this topic helpful?
Document Information
Modified date:
16 June 2018
UID
swg21160634