我不明白为什么这会导致我的程序崩溃!?当我编译它时,它会在程序结束时停止响应。
void rotate90(Image& image)
{
Pixel * tempPixel = new Pixel[(image.infoHeader.biWidth * image.infoHeader.biHeight)];
for(int r = 0; r < image.infoHeader.biHeight; r ++)
{
for(int c = 0; c < image.infoHeader.biWidth; c++)
{
int f = c+(r*image.infoHeader.biWidth);
int t = (image.infoHeader.biHeight - r - 1) + (image.infoHeader.biWidth-c-1);
tempPixel[t] = image.pixels[f];
}
}
image.pixels =tempPixel ;
delete[] tempPixel;
}
最佳答案
您必须在使用该变量之前声明该变量...
Pixel * tempPixel = new Pixel[image.infoHeader.biWidth * image.infoHeader.biHeight];
请注意,您必须在函数末尾使用 delete[]
释放临时数组。 (否则你有内存泄漏)。为了自动执行此操作并避免异常安全问题,您应该使用智能指针,例如 scoped_array<Pixel>
来自 Boost 或(如果您有支持新 C++ 标准的编译器)unique_ptr<Pixel[]>
.
更好的是:你可以只使用 std::vector<Pixel>
std::vector<Pixel> tempPixel(image.infoHeader.biWidth * image.infoHeader.biHeight);
让它处理分配/解除分配。
先发制人的答案更正(由于你的 new question ):如果最后你要分配 tempPixel
至 image.pixels
, 那么你一定不能 delete[]
tempPixel
, 否则 image
将替换为指向已释放内存的指针。
但是你有更大的问题:当你替换 image.pixels
时您没有释放它之前指向的内存。所以你应该释放那个内存然后然后分配tempPixel
所有这一切都假设 image.pixels
分配了 new
并将与 delete[]
一起解除分配(否则你会得到不匹配的分配函数/运算符)。
顺便说一句,如果您的图像只是某种 Windows DIB (BMP) 的包装器,从标题字段名称看来您没有考虑像素行是 4 字节对齐的事实(因此,如果您的图像不是 32bpp,则必须分配更多内存并相应地执行像素复制。
关于c++ - 我不明白为什么这会导致我的程序崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8424303/