Interesting question of memory leak detected by vagrind of forked process
I know If I malloc a memory, I need to free both in parent and forked process, but how about there is no explicit malloc&new call, here is the simple code valgrind throw me the warning of possibly memory loss:
<verbatim>
#include <string>
#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <sys/wait.h>
#include <sched.h>
using namespace std;
struct WorkData {
int cpu;
string commandStr;
};
static void* work( void* data )
{
}
#define MAX_CONCURRENCY 20
int main() {
WorkData workData[ MAX_CONCURRENCY ];
pid_t pid[ MAX_CONCURRENCY ];
int curLevel = 0;
workData[curLevel].commandStr = string("runMM5 1 2 3 4 5");
workData[curLevel].cpu = curLevel;
if ( (pid[curLevel] = fork()) == 0 ) {
work( reinterpret_cast<void*> ( &(workData[curLevel])));
exit( 0 );
}
}
</verbatim>
build:
g++ -ggdb -g -o test.exe test.cpp
run:
valgrind --leak-check=yes --trace-children=yes ./test.exe
==27730== 41 bytes in 1 blocks are possibly lost in loss record 1 of 1
[rong@tux7 tmp]$ ==27730== at 0x4A06205: operator new(unsigned long) (vg_replace_malloc.c:167)
==27730== by 0x34FCC9B8A0: std::string::_Rep::_S_create(unsigned long, unsigned long, std::allocator<char> const&) (in /usr/lib64/libstdc++.so.6.0.8)
==27730== by 0x34FCC9C3A4: (within /usr/lib64/libstdc++.so.6.0.8)
==27730== by 0x34FCC9C551: std::string::string(char const*, std::allocator<char> const&) (in /usr/lib64/libstdc++.so.6.0.8)
==27730== by 0x400A3A: main (test.cpp:30)
If I don't fork, then there is no memory loss, anybody have an idea why this is happening?
|