Liam Norris Liam Norris - 7 days ago 6
C++ Question

C++ - Heap Corruption on UInt32*

I am currently programming a game on C++ and am working with the SDL 2.0 library.

I am attempting to disect a 32x32 image from a texture to store as a tile and am attempting to recreate it from the pixels of a texture. When I run this code and attempt to edit the Uint32* by a for loop, I can edit it but once I try to creat the image, I get a heap corruption.

I currently have this code running:

Uint32* pixels = (Uint32*)m_pSprite->GetPixels();
int pixelCount = (m_pSprite->GetPitch() / 4) * m_pSprite->GetHeight();

int tileOffset = 0;
int spriteSheetOffset = 0;
int widthOffset = m_pSprite->GetWidth();

Uint32* tilePixels = new Uint32(32);
for (int y = 0; y < 32; y++)
{
tileOffset = (y * 32);
spriteSheetOffset = (y * widthOffset);
for (int x = 0; x < 32; x++)
{
tilePixels[tileOffset + x] = pixels[spriteSheetOffset + x];
}
}

int tilePitch = 32*4;
SDL_Texture* texture = SDL_CreateTexture(backBuffer.GetRenderer(), SDL_PIXELFORMAT_RGB888, SDL_TEXTUREACCESS_TARGET, TILE_WIDTH, TILE_HEIGHT);


I can see that there is something wrong with the Uint32* variable and that this is obviously not a best practice but I am still wrapping my head around what can and cannot be done, and what is the best way etc.

Does anyone have an explanation of what could be happening?

qxz qxz
Answer
Uint32* tilePixels = new Uint32(32);

This is dynamically allocating a single Uint32, and initializing/constructing it to the value 32. It seems you want a 32*32 array of those. Try this:

Uint32* tilePixels = new Uint32[32*32]; // brackets allocate an array

Although, since the size of your array is static (known at compile-time), it would be best to just use a stack-allocated array instead of a dynamic one:

Uint32 tilePixels[32*32];

See if that fixes it.

Comments