Shreeravi 0 Newbie Poster

I have a situation where I have to scan some FTP Servers every 5 seconds to check for some specific files and download them if they exist. I use a Shell script to do FTP download operation and call it using C++ system call in a separate thread. (I am on Linux)
Here is how the code skeleton looks like:

//Main thread
handle_timeout  //called every 5 seconds
{ 
       HandleFTPOper();
}

HandleFTPOper()
{
      //Allocate  memory in heap here
      FTPLoginDetails pFTPLogin = new FTPLoginDetails();
     
      //fill the allocated memory (FTPLoginDetails) here
      .... 

      //Create a child thread and pass the FTP Login details to the thread as input argument
      ACE_Thread::spawn((ACE_THR_FUNC)&Download, pFTPLogin); 

      //return to main thread, no need to join/wait for the created thread.
      return;
}

//child thread
static void* Download(FTPLoginDetails *pData)
{
     //Pass the FTP Login Details to shell script which will download some files
     system("Download.sh -a arguments");
    
     //delete the input data
     delete [] pData;
     return 0;
}

This code is working but it is leading to a memory leak. (the main process restarts after about an hour (i.e. after calling the download function around 720 times) owing to lack of memory for other variables in the system. I tried to reason as follows:

1) The pData is not being deleted somehow and getting leaked.
But this was not the case. I removed the pData heap allocation and declared it as a (stack) variable inside the child-thread, hard coded the log in details. But, there was still a memory leak.

2) The created threads are not getting destroyed.
This is the most likely possibility. Note that I deliberately left out any join or wait condition in the main thread as I do not want the main thread to wait for the child thread's FTP Operation to complete.

To sum up, I am creating a new thread every 5 seconds and leaving them on their own to do the FTP Operation and wind up. I don't bother to wait in the main thread after creating them and go on doing my things. I know it doesn't sound like a good design, but I am working on a very restrictive base code.

Now, the reason for memory leak could be because of the created child threads not destroyed.
But am I assuming anything wrong here? Isn't a ACE thread supposed to destory itself and free its resources when it "falls through" the function? What could be the problem?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.