C ++ - UInt32上的堆损坏*

时间:2016-11-27 05:20:26

标签: c++ sdl-2 heap-corruption

我目前正在使用C ++编写游戏,并正在使用SDL 2.0库。

我试图从纹理中删除32x32图像以存储为图块,并尝试从纹理的像素重新创建它。当我运行此代码并尝试通过for循环编辑Uint32 *时,我可以编辑它,但是一旦我尝试创建图像,我就会出现堆损坏。

我目前正在运行此代码:

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);

我可以看到Uint32 *变量有问题,这显然不是最好的做法,但我仍然围绕着能做什么和不能做什么,以及最好的方式等等。

有没有人对可能发生的事情有解释?

1 个答案:

答案 0 :(得分:3)

Uint32* tilePixels = new Uint32(32);

这是动态分配 Uint32,并将其初始化/构建为值32。看来你想要一个32 * 32 数组。试试这个:

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

虽然,因为数组的大小是静态的(在编译时已知),所以最好只使用堆栈分配的数组而不是动态数组:

Uint32 tilePixels[32*32];

看看是否能解决问题。

相关问题