user200257
user200257

Reputation: 53

What does access violation mean?

I'm new to C++ and do not understand why I am getting the error "Access Violation Reading Location". Here is my code:

gdiscreen();
int startX = 1823 - minusX;
int startY = 915 - minusY;
for (int i = startX; i < startX + 61; i++)
{
    for (int j = startY; j < startY + 70; j++)
    {
        Color pixelColor;
        bitmap->GetPixel(i, j, &pixelColor);
        cout << pixelColor.GetValue() << " ";
    }
    cout << endl;
}

gdiscreen() can be found here: http://forums.codeguru.com/showthread.php?476912-GDI-screenshot-save-to-JPG

Upvotes: 3

Views: 15504

Answers (1)

Tom&#225;š Zato
Tom&#225;š Zato

Reputation: 53317

Access violation or segmentation fault means that your program tried to access a memory that was not reserved in the scope.
Have a few examples how to achieve this:

Leaving bounds of array:

int arr[10];
for(unsigned char i=0; i<=10; i++)  //Will throw this error at i=10
    arr[i]=0;

Note: In the code above, I use unsigned char to iterate. Char is one byte, so unsigned char is 0-255. For larger numbers, you may need unsigned short (2 bytes) or unsigned int (4 bytes).

Accidentally calculating with pointer instead of integer

int ah = 10;
int *pointer = &ah;   //For some reason, we need pointer
pointer++;   //We should've written this: (*pointer)++ to iterate value, not the pointer
std::cout<<"My number:"<<*pointer<<'\n';  //Error - accessing ints address+1

I intentionally started with broad explanation. You wanted to know what access violation is at the first place. In your particular code, I'm very sure you messed up with i and j boundaries. Do some std::cout debug.

Upvotes: 5

Related Questions