[英]C++ - Heap Corruption on UInt32*
I am currently programming a game on C++ and am working with the SDL 2.0 library. 我目前正在使用C ++编写游戏,并正在使用SDL 2.0库。
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. 我试图从纹理中删除32x32图像以存储为图块,并尝试从纹理的像素重新创建它。 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.
当我运行此代码并尝试通过for循环编辑Uint32 *时,我可以编辑它,但是一旦我尝试创建图像,我就会出现堆损坏。
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. 我可以看到Uint32 *变量有问题,这显然不是最佳实践,但我仍然围绕着能做什么和不能做什么,以及最好的方法等等。
Does anyone have an explanation of what could be happening? 有没有人解释可能发生的事情?
Uint32* tilePixels = new Uint32(32);
This is dynamically allocating a single Uint32
, and initializing/constructing it to the value 32
. 这是动态分配单个
Uint32
,并将其初始化/构造为值32
。 It seems you want a 32*32 array of those. 看起来你想要一个32 * 32 阵列 。 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. 看看是否能修复它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.