To return a big struct "MODULEENTRY32" from WINAPI I want to use a pointer, but need to allocate memory in the heap inside the function without deleting it. Then, out of the function when I don't want to use that struct anymore I know that I should use the keyword delete to free memory.
#include <iostream>
#include <cstring>
#include <Windows.h>
#include <TlHelp32.h>
MODULEENTRY32* GetModuleEntry(const char *module_name, int PID)
{
    HANDLE moduleSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, PID);
    if (moduleSnapshot != INVALID_HANDLE_VALUE)
    {
        MODULEENTRY32 *moduleEntry = new MODULEENTRY32;             // Remember to delete if don't want leak
        moduleEntry->dwSize = sizeof(MODULEENTRY32);
        if (Module32First(moduleSnapshot, moduleEntry)) {
            do {
                if (strcmp(moduleEntry->szModule, module_name) == 0) {
                    return moduleEntry;
                }
            } while (Module32Next(moduleSnapshot, moduleEntry));
        }
        CloseHandle(moduleSnapshot);
    }
    return nullptr;
}
int main()
{
    int myRandomPID = 123;
    MODULEENTRY32* p = GetModuleEntry("mymodule.dll", myRandomPID);
    if (!p) {
        std::cout << "Obviously you didn't found your random module of your random PID " << std::endl;
    }
    delete p;   // I just don't want to do this
    return 0;
}
How could I avoid having to free memory in main function? unique_ptr?
EDIT: Possible solution
#include <iostream>
#include <cstring>
#include <Windows.h>
#include <TlHelp32.h>
bool GetModuleEntry(const char *module_name, int PID, MODULEENTRY32* moduleEntry)
{
    HANDLE moduleSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, PID);
    if (moduleSnapshot != INVALID_HANDLE_VALUE)
    {
        moduleEntry->dwSize = sizeof(MODULEENTRY32);
        if (Module32First(moduleSnapshot, moduleEntry)) {
            do {
                if (strcmp(moduleEntry->szModule, module_name) == 0) {
                    CloseHandle(moduleSnapshot);
                    return true;
                }
            } while (Module32Next(moduleSnapshot, moduleEntry));
        }
        CloseHandle(moduleSnapshot);
    }
    return false;
}
int main()
{
    int myRandomPID = 123;
    MODULEENTRY32 moduleEntry;
    if (!GetModuleEntry("mymodule.dll", 123, &moduleEntry)) {
        std::cout << "Obviously you didn't find your random module of your random PID " << std::endl;
    }
    return 0;
}
 
    