2011-12-07 370 views
0

我不明白为什么这会导致我的程序崩溃!?当我编译它使程序结束然后停止响应。我不明白为什么这会导致我的程序崩溃?

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; 
} 
+1

删除它这不是编辑的问题的方式......你应该添加你遇到* *后的老问题,身体,否则目前的答案变得看似无关的新的问题的信息。 –

回答

1

你必须在使用前声明变量...

Pixel * tempPixel = new Pixel[image.infoHeader.biWidth * image.infoHeader.biHeight]; 

请注意,您必须在函数结束与delete[](否则你有内存泄漏)解除分配临时数组。为了使其自动化并避免异常安全问题,您应该使用智能指针,如Boost的scoped_array<Pixel>或(如果您的编译器支持新的C++标准)unique_ptr<Pixel[]>

更妙的是:你可以只使用一个std::vector<Pixel>

std::vector<Pixel> tempPixel(image.infoHeader.biWidth * image.infoHeader.biHeight); 

,让它处理分配/释放。


抢答校正(因您的new question):如果你到底要分配给tempPixelimage.pixels,那么你一定不能delete[]tempPixel,否则image将具有指针解除分配内存更换。

但你有更大的问题:当你更换image.pixels你是不是重新分配它指向先前的记忆。所以你应该取消分配内存和然后分配tempPixel它。

这一切都假设image.pixels被分配了new并将被释放与delete[](否则您会得到分配函数/运算符不匹配)。


顺便说一句,如果你的形象仅仅是某种形式的包装为Windows DIB(BMP),因为它从标题似乎字段,你都没有考虑到这样的事实名字是像素线是4字节对齐(如果您的图像不是32bpp,则必须分配更多内存并相应地执行像素复制)。

+0

非常感谢! – Jake

+1

@Jake。如果我的答案解决了您的问题,您可以考虑将其标记为已接受。 :) –

0

变化数组声明

tempPixel[] = new Pixel[(image.infoHeader.biWidth * image.infoHeader.biHeight)]; 

Pixel* tempPixel = new Pixel[(image.infoHeader.biWidth * image.infoHeader.biHeight)]; 

,并记得

delete[] tempPixel; 
相关问题