Search code examples
memory-leaksguiddangling-pointer

OLECHAR used as pointer - will it dangling pointer if not nullptr? Function CoTaskMemFree()


I generate a GUID and then save it in OLECHAR* with StringFromCLSID(). If I create a function which returns an OLECHAR and not nullptr the OLECHAR after using CoTaskMemFree() - will it cause dangling pointer? I want to return just the value but don't know if it will cause problem. This is the code:

OLECHAR* generateGUIDString()
{
    GUID guid;
    CoCreateGuid(&guid);
    OLECHAR* guidString;
    StringFromCLSID(guid, &guidString);
    return guidString;
}

Otherwise I have to write multiple times:

  GUID guid;
  CoCreateGuid(&guid);
  OLECHAR* guidString;
  StringFromCLSID(guid, &guidString);
  //use it here in some process
  CoTaskMemFree(guidString);
  guidString = nullptr;

I just want to ensure there is no memory leak or dangling pointers and the program works fine.


Solution

  • As it's C++, you can return std::wstring:

    std::wstring generateGUIDString()
    {
        GUID guid;
        CoCreateGuid(&guid);
        OLECHAR* guidString;
        StringFromCLSID(guid, &guidString);
        std::shared_ptr<OLECHAR> ptr(guidString, [](OLECHAR* ptr)
            {
                CoTaskMemFree(ptr);
            });
        return ptr.get();
    }