My Texture to HBITMAP function leaks and I don't know why...

Started by
3 comments, last by rogueyoshi 7 years, 11 months ago

It works fine, but will crash about 20 seconds after execution on my machine. I can't figure out where the leak is.


HBITMAP CDirectXWrapper::Capture()
{
	D3D11_TEXTURE2D_DESC textureDesc = m_textureDesc;
	textureDesc.Usage = D3D11_USAGE_STAGING;
	textureDesc.BindFlags = 0;
	textureDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE;
	//textureDesc.MiscFlags = 0;

	ComPtr<ID3D11Texture2D> texture;
	DX::ThrowIfFailed(
		m_d3dDevice->CreateTexture2D(&textureDesc, nullptr, texture.ReleaseAndGetAddressOf())
	);
	m_d3dContext->CopyResource(texture.Get(), m_texture.Get());
	
	D3D11_MAPPED_SUBRESOURCE mappedSubresource;
	m_d3dContext->Map(texture.Get(), D3D11CalcSubresource(0, 0, 0), D3D11_MAP_READ_WRITE, 0, &mappedSubresource);
	
	// Copy subresource data to buffer.
	uint8_t *source = reinterpret_cast<uint8_t*>(mappedSubresource.pData);
	uint8_t *destination = new uint8_t[textureDesc.Width * textureDesc.Height * 4];
	size_t size = std::min<size_t>(textureDesc.Width * 4, mappedSubresource.RowPitch);

	for (size_t h = 0; h < textureDesc.Height; h++)
	{
		memcpy_s(destination, textureDesc.Width * 4, source, size);
		source += mappedSubresource.RowPitch;
		destination += textureDesc.Width * 4;
	}

	destination -= textureDesc.Width * textureDesc.Height * 4;

	// Copy buffer to bitmap.
	HDC hDC = GetDC(NULL);
	HBITMAP	hBitmap = CreateCompatibleBitmap(hDC, textureDesc.Width, textureDesc.Height);
	SetBitmapBits(hBitmap, textureDesc.Width * textureDesc.Height * 4, destination);

	ReleaseDC(NULL, hDC);

	return hBitmap;
}

Any help would be appreciated.

Advertisement
For starters, you assign new[]’d memory to destination, but you don’t delete[] it. You may also consider using std::vector instead, so you only need to make an allocation for every time the source image grows, instead of allocating every frame.

For starters, you assign new[]’d memory to destination, but you don’t delete[] it. You may also consider using std::vector instead, so you only need to make an allocation for every time the source image grows, instead of allocating every frame.

Could I have a code example?


// assuming std::vector<uint8_t> CDirectXWrapper::image_buffer;

image_buffer.resize(textureDesc.Width * textureDesc.Height * 4); // may or may not trigger realloc
uint8_t* destination = image_buffer.data();

// assuming std::vector<uint8_t> CDirectXWrapper::image_buffer;

image_buffer.resize(textureDesc.Width * textureDesc.Height * 4); // may or may not trigger realloc
uint8_t* destination = image_buffer.data();

Thank you! I was wondering if it was because I forgot to deallocate something DX related but, ha.

This topic is closed to new replies.

Advertisement