我不明白为什么会导致我的程序崩溃? [英] I don't understand why this is causeing my program to crash?

查看:144
本文介绍了我不明白为什么会导致我的程序崩溃?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I don't understand why this is causing my program to crash!? when i compile it makes it to then end of the program then stops responding.

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 [] (否则你有内存泄漏)。要使这个自动化并避免异常安全的问题,你应该使用一个聪明的指针,如Boost的 scoped_array< Pixel> 或(如果你有一个编译器支持新的C ++标准) unique_ptr< Pixel []>

Notice that you must deallocate the temporary array at the end of the function with delete[] (otherwise you have a memory leak). To make this automatic and avoid issues with exception safety, you should be using a smart pointer, like scoped_array<Pixel> from Boost or (if you have a compiler that supports the new C++ standard) unique_ptr<Pixel[]>.

更好: $ c> std :: vector< Pixel>

Even better: you could just use a std::vector<Pixel>

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

并处理分配/取消分配。

and let it deal with allocation/deallocation.

优先回答修正(由于您 tempPixel 分配给 image.pixels ,那么你不能 delete [] tempPixel ,否则<$ c

Preemptive answer correction (due to your new question): if in the end you are going to assign tempPixel to image.pixels, then you must not delete[] tempPixel, otherwise image will be replaced with a pointer to deallocated memory.

但是你有更大的问题:当你替换 image.pixels 您不是释放之前指向的内存。因此,您应该分配 内存,然后分配 tempPixel

But you have bigger problems: when you replace image.pixels you are not deallocating the memory it was pointing to previously. So you should deallocate that memory and then assign tempPixel to it.

所有这些假设 image.pixels 分配了 new ,并且将被释放 delete [] (否则会出现分配函数/运算符不匹配)。

All this assuming that image.pixels was allocated with new and is going to be deallocated with delete[] (otherwise you get a mismatch of allocation functions/operators).

顺便说一句,如果你的图像只是某种Windows DIB(BMP)的封装,因为它似乎从头字段名称,你没有考虑到这一事实,像素行是4字节对齐所以,如果你的图像不是32bpp,你必须分配更多的内存和相应地执行像素复制)。

By the way, if your image is just some kind of wrapper for a Windows DIB (BMP) as it seems from the header fields names you are not taking into account the fact that pixel lines are 4-byte aligned (so, if your image is not 32bpp, you must allocate more memory and perform the pixel copy accordingly).

这篇关于我不明白为什么会导致我的程序崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆