UTexture2D::UpdateTextureRegions() crashes on development configuration

In my project I’m making heavy use of “raw” texture updates, like this:

	for (int j = 0; j < HitTextureSize.Y; j++)
	{
		SIZE_T BufferOffset = j * HitTextureSize.X * 4;

		for (int i = 0; i < HitTextureSize.X; i++)
		{
			// The selection associated with the pixel under process
			uint8 CurrentIteration = HitTextureDataCache[BufferOffset] - 1;
			// Stop the loop if current iteration is found
			int k; for (k = 0; k < Num && SelectionList[k] != CurrentIteration; k++);

			if (k >= Num)
			{
				// Calc desaturated value
				const uint8 DesaturatedValue = (FMath::Min(BackgroundTextureDataCache[BufferOffset RED_CHANNEL], FMath::Min(BackgroundTextureDataCache[BufferOffset GREEN_CHANNEL], BackgroundTextureDataCache[BufferOffset BLUE_CHANNEL])) +
					FMath::Max(BackgroundTextureDataCache[BufferOffset RED_CHANNEL], FMath::Max(BackgroundTextureDataCache[BufferOffset GREEN_CHANNEL], BackgroundTextureDataCache[BufferOffset BLUE_CHANNEL]))) * 0.333;

				// (k >= Num) means that the current iteration was not found in the selection list
				// Thus we desaturate this zone
				FMemory::Memset(BackgroundTextureDataCurr + BufferOffset, DesaturatedValue, 3 * sizeof(uint8));
			}

			BufferOffset += 4;
		}
	}
}

QUICK_LOG("Here");

// Texture region
FUpdateTextureRegion2D Region(0, 0, 0, 0, BackgroundTextureSize.X, BackgroundTextureSize.Y);
// Update resource
BackgroundTexture->UpdateTextureRegions(0, 1, &Region, BackgroundTextureSize.X * 4, 4, BackgroundTextureDataCurr);

The exception raised are ACCESS_VIOLATION on two tested devices and INT_DIVIDED_BY_ZERO on a third device. Without the call to UpdateTextureRegions() no crash occurs. The problem seems related to the FMemory::Memset() statement: if I comment it out no crash occurs (but of course the data is not updated).

I also tried to replace the Memset with 3 array accesses, but it crashes as well. Other pieces of code that uses UpdateTextureRegions() seems to work. The source code can be found here on GitHub. Any idea?

UPDATE: Apparently it works if packaged in shipping configuration

It’s just that I’m so stupid…

After lots of experiments I discovered the source of the ACCESS_VIOLATION exception.

The actual UpdateTextureRegions code enqueues a render command processed by the render thread. Unfortunately, I guess that by the time the code is executed the stack of my function has already been deallocated, and thus the pointer to Region doesn’t point to anything.

In the end I simply declared a class variable FUpdateTextureRegion2D *Region and everything is finally working.

Thanks for posting! Was having same issue!!!