Access violation reading location 0xFDFDFDFD

1.6k views Asked by At

I would like to get some help, i am getting this error while running application

Exception thrown at 0x0029B23D in ConsoleApplication1.exe: 0xC0000005: Access violation reading location 0xFDFDFDFD. If there is a handler for this exception, the program may be safely continued.

I think the problem is accessing non-paged memory region

Here is my code

int ** create_tab(int size)
{
    int ** tab = new int *[size];
    for (int i = 0; i < size; i++)
    {
        tab[i] = new int[size];
    }
    return tab;
}
int definition(int direction, int px, int py, int tab)
{
    switch (tab[&py][&px]) {
    case 1:
        tab[&py][&px] = 0;
        direction = direction - 1;
        break;
    case 0:
        tab[&py][&px] = 1;
        direction = direction + 1;
        break;
    }
    return direction;
}
int main()
{
    int px = 0;
    int py = 0;
    int direction = 0;
    int size = 0;
    int steps = 0;
    int steps_done = 0;
    for (int steps_done = 0;steps_done < steps;steps_done++)
    {
        system("cls");
        turningaround(direction);
        moves(direction, px, py);
        looping_tab(px, py, size);
        definition(direction, px, py, ** tab);
        printing(size, ** tab);
}

The problem comes from definition function, the program starts but when i try to continue it just appears again and again.

1

There are 1 answers

0
Bo Persson On

Using tab[&py][&px] happens to make the compiler accept the code, but it is just totally wrong. You accidentally tell the compiler that &py is an array and tab is the index, when it should be the other way round.

That the indexing "works" depends on this quirk of the C language:

With arrays, why is it the case that a[5] == 5[a]?

I guess the intended way to use the function was

int definition(int direction, int px, int py, int** tab)
{
    switch (tab[py][px]) {
    case 1:
        tab[py][px] = 0;
        direction = direction - 1;
        break;
    case 0:
        tab[py][px] = 1;
        direction = direction + 1;
        break;
    }
    return direction;
}

but that doesn't work either, as the compiler cannot know the lengths of the rows in the matrix. That depends on the size parameter passed to the create_tab function, which the definition knows nothing about.

Also, if the function had worked, you would have to collect the returned direction value in main. Otherwise the update will be lost.

If you intend this to be C++, you could make tab a std::vector<std::vector<int>> to avoid most of these problems.