Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...