Search code examples
c++memory-leakstexturesloadingdirectx-11

Memory leak when loading a 2D texture with DX11


Loading in a texture with no real issues, the ID3D11Texture2D that I'm using to temporarily grab the D3D11_TEXTURE2D_DESC info seems to not delete properly.

If I don't bother using the ID3D11Texture2D item I don't have memory leaks. When I do use it, despite deleting it after getting what I need, it is left over on shutdown when using the ReportLiveObjects function.

I've tried using my own * and manually deleting it, I've tried using a ComPtr and trying the various ways to free one of those up.

Microsoft::WRL::ComPtr<ID3D11Texture2D> pTextureInterface = nullptr;
ID3D11Resource *res = nullptr;

HRESULT hres = DirectX::CreateWICTextureFromFileEx(m_pDev, const_cast<wchar_t*>(wStrAddress.c_str()), 0, D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, DirectX::WIC_LOADER_IGNORE_SRGB, &res, tempTex.ReleaseAndGetAddressOf());

tempTex->GetResource(&res);
res->QueryInterface<ID3D11Texture2D>(&pTextureInterface);
D3D11_TEXTURE2D_DESC desc;
pTextureInterface->GetDesc(&desc);

RECT r;
r.left = 0;
r.top = 0;
r.right = desc.Width;
r.bottom = desc.Height;

if (pTextureInterface != nullptr)
{
    pTextureInterface.ReleaseAndGetAddressOf();
    pTextureInterface = nullptr;
}
if (res != nullptr)
{
    res->Release();
    res = nullptr;
}

When I create and use the pTextureInterface I get a DirectX memory leak warning for every texture I load with a Refcount of 1. If I don't bother to use pTextureInterface at all I have no leaks and everything loads and displays properly (except their dimensions as I then am manually setting the rectangle bounds of the source image)

I realize this is probably some tiny little oversight but I have been unable to find a working solution all day, any help would be appreciated.


Solution

  • At invocation tempTex->GetResource(&res); naked pointer acquired during the call to CreateWICTextureFromFileEx is overwritten without releasing it. So the reference counter for that object is not decremented and object leaks. It looks like tempTex->GetResource(&res); is not needed at all.