Hi,
I am getting a memory leak while running unit test in C++.
You can see definition of the function, and the map used by this function which casuses unit test memory leak;
const char* myMap [] =
{
"INPUT1" , "OUTPUT1",
"INPUT2" , "OUTPUT2",
"INPUT3" , "OUTPUT3",
"INPUT4" , "OUTPUT4",
"INPUT5" , "OUTPUT5",
"INPUT6" , "OUTPUT6",
"INPUT7" , "OUTPUT7",
"INPUT8" , "OUTPUT8",
"INPUT9" , "OUTPUT9",
"INPUT10" , "OUTPUT10",
"THE_END"
};
const std::string Class::translateInput( const std::string& tag )
{
static bool initialized = false;
static map<std::string, std::string> m;
if (!initialized)
{
initialized = true;
unsigned long i = 0;
static const std::string s = "THE_END";
while( s != myMap[i])
{
std::string key = myMap[i];
printf("\n 1. key is set to %s \n", myMap[i] );
printf("\n m[ key ] is set to %s \n", myMap[i+1] );
m[ key ] = myMap[i+1];
i+=2;
};
}
Here is the output of valgrind :
Block size: 29, Address: 0x5f40f44, Back Trace:
2. /usr/lib/i386-linux-gnu/libstdc++.so.6(std::string::_Rep::_S_create(unsigned int, unsigned int, std::allocator<char> const&)) [0x455f7d4]
3. /usr/lib/i386-linux-gnu/libstdc++.so.6(std::string::_M_mutate(unsigned int, unsigned int, unsigned int)) [0x455fab4]
4. /usr/lib/i386-linux-gnu/libstdc++.so.6(std::string::_M_replace_safe(unsigned int, unsigned int, char const*, unsigned int)) [0x455fc42]
5. /usr/lib/i386-linux-gnu/libstdc++.so.6(std::string::assign(char const*, unsigned int)) [0x455fcf9]
6. /usr/lib/i386-linux-gnu/libstdc++.so.6(std::string::operator=(char const*)) [0x455ff06]
7. MyClass::translateInput(std::string const&)) [0x43025c8]
And it indicates the line where string assignment is made as the following ;
m[ key ] = myMap[i+1];
I've put traces before, and after this line. And there is no error while making assignment after initialization. After the unit test is teared down, it gives the above output.
I have no idea about the cause of memory leak. As you can also see, there is no pointer, or memory initialization in the function. And When I put the correct output of this function( translateInput ) manually ( by commenting out the call of function ), there is no leak. Whenever I use this function, I get the memory leak I mentioned above.
P.S: All members and functions of this class, MyClass, is static.
Could you please help about the possible reasons which cause memory leak in this state ?
Thanks in advance,
Cranberries