Search code examples
c++window

Kill process and release memory in c++


I have a service that it creates a process and then frees its memory. I use createprocess() function and then close handle of process and thread, this is my code:

        if (CreateProcessA(NULL,
                           zAppName,//{ pointer to command line string }
                           NULL,     //{ pointer to process security attributes }
                           NULL,     //{ pointer to thread security attributes }
                           TRUE,     //{ handle inheritance flag }
                           0,
                           NULL,     //{ pointer to new environment  block }
                           NULL,     //{ pointer to current directory name }
                           &StartupInfo,    //{ pointer to STARTUPINFO }
                           &ProcessInfo))
    {
        WaitForSingleObject(ProcessInfo.hProcess,WaitMiliSec);
        GetExitCodeProcess(ProcessInfo.hProcess, &Result);

        CloseHandle(ProcessInfo.hProcess);
        CloseHandle(ProcessInfo.hThread);    

        CloseHandle(hRead);
        CloseHandle(hWrite);
        return (Result);
    }

But after closehandle() function, hProcess and hThread still have value!!! and each time my service runs this code the memory increases and doesn't decrease!!!Is this a memory leak? what should I do?


Solution

  • As the process is loaded into the memory following elements are loaded : 1.code 2.memory 2.PCB 4.Data etc. When you close handles only some part of heap (assuming that you are using malloc to create handlers) is freed. So rest of elements still remains into the process stack. So you can't guarantee that memory is not freed. yes hProcess and hThread might have some values that can create confusion. But these pointers hProcess and hThread will be called as "dangling pointers". So it is a good practice to assign a null value to the pointers after de-allocation.