Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

c++ - I don't understand why this is causeing my program to crash?

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have to declare that variable before using it...

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

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[]>.

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.


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.

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.

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


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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...