2

I'm trying to make an image 4 times its size by making a temp image, with double the original images width and height.Then take information from each pixel on the original image and give it to 4 pixels on the temp image. Something like this.

Original image:

[1] [2]

[3] [4]

To temp image:

[1][1] [2][2]

[1][1] [2][2]

[3][3] [4][4]

[3][3] [4][4]

But I get an access violation writing location 0xCDCDCDCD. Here is my function code:

void makeBigger(Image* plain)
{
Image temp;

temp.height = plain->height * 2;
temp.width = plain->width * 2;

temp.pixels = (Pixel**)malloc(sizeof(Pixel*) * temp.height);
for (int i = 0, k = 0; i < temp.height; i+2, k++)
{
    temp.pixels[i] = (Pixel*)malloc(sizeof(Pixel) * temp.width);
    for (int j = 0, g = 0; j < temp.width; j+2, g++)
    {
        temp.pixels[i][j].r = plain->pixels[k][g].r;
        temp.pixels[i][j+1].r = plain->pixels[k][g].r;
        temp.pixels[i+1][j].r = plain->pixels[k][g].r;
        temp.pixels[i+1][j+1].r = plain->pixels[k][g].r;

        temp.pixels[i][j].g = plain->pixels[k][g].g;
        temp.pixels[i][j+1].g = plain->pixels[k][g].g;
        temp.pixels[i+1][j].g = plain->pixels[k][g].g;
        temp.pixels[i+1][j+1].g = plain->pixels[k][g].g;

        temp.pixels[i][j].b = plain->pixels[k][g].b;
        temp.pixels[i][j+1].b = plain->pixels[k][g].b;
        temp.pixels[i+1][j].b = plain->pixels[k][g].b;
        temp.pixels[i+1][j+1].b = plain->pixels[k][g].b;
    }
}

*plain = temp;

}

On the violation seems to occur on the line

temp.pixels[i+1][j].r = plain->pixels[k][g].r;

as that is when the program breaks and the error shows. What is causing this violation and why? What can be done to fix this?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
zaylan
  • 23
  • 4

2 Answers2

4

Inside the outer loop, at every iteration:

  • You initialize temp.pixels[i] to point to a properly allocated memory block
  • You attempt to write into the memory block pointed by temp.pixels[i]
  • You attempt to write into the memory block pointed by temp.pixels[i+1]

But since you do not initialize temp.pixels[i+1] to point to a properly allocated memory block, attempting to access memory with this variable leads to a memory access violation (or more generally, undefined behavior).

barak manos
  • 29,648
  • 10
  • 62
  • 114
3

The magic value 0xCDCDCDCD indicates you're accessing uninitialized heap memory:

0xCDCDCDCD : Used by Microsoft's C++ debugging runtime library to mark uninitialised heap memory

Specifically, you're reading that value from a pointer on the heap, and then attempting to dereference it, causing the illegal memory access.

See In Visual Studio C++, what are the memory allocation representations? for more magic values used by MSVC.

Community
  • 1
  • 1
Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328