Snake game with c++ OOB

0

I wrote a snake game in c++ in console and i have some issues that I can't understand. Could anyone help me? According to code below:

class Snake : public Fruit{
    private:
        int head;
        short dir_x;    //-1 (left or down) / +1 (right or up)
        short dir_y;

        friend class Game;

        int base_length = 3;    // base length of snake on start of the game
        const int length = Board::global_x * Board::global_y;   // max length
        int prev_tailPos[2];    // previous tail position (end of snake)
        int tail;               // tail is sum of base_length and score             
        int time = 100;         //  delay for snake

        struct Body{
            int body_pos[2]; // position of every element of snakes body
            Body* higherEl;  // point element nearer head element
        };
        Body* body = new Body[length];  // array for body of snake
};

With that order everything is fine, but if I put definition of struct Body, and body on top of that class, just like that:

class Snake : public Fruit{
    private:
        struct Body{
            int body_pos[2]; // position of every element of snakes body
            Body* higherEl;  // point element nearer head element
        };
        Body* body = new Body[length];  // array for body of snake

        int head;
        short dir_x;    //-1 (left or down) / +1 (right or up)
        short dir_y;

        friend class Game;

        int base_length = 3;    // base length of snake on start of the game
        const int length = Board::global_x*Board::global_y; // max length
        int prev_tailPos[2];    // previous tail position (end of snake)
        int tail;               // tail is sum of base_length and score             
        int time = 100;         //  delay for snake
};

After I stop the game this error shows up:

> Unhandled Exception at 0x76C40860 (sechost.dll) in Snake.exe: 
> 0xC0000005: Access violation reading location 0x00000004`

Can someone help me why that is a problem?

c++
oop
access-violation
asked on Stack Overflow Sep 19, 2019 by Tojmak • edited Sep 21, 2019 by Yukulélé

1 Answer

3

It seems that in your second example, the variable length is undefined at the time of evaluating
Body* body = new Body[length];.

This is most likely your problem.

To explain this a little further, you need to understand that:
The order of the declaration of variables inside a class/struct is important.

To illustrate:

class Data{
    int a = 10;
    int b = a;
};

In this example, both a and b will be equal to 10.
However, in a case like this:

class Data{
    int b = a;
    int a = 10;
};

a will be 10 and b will have a trash value.
This is because when evaluating int b = a;. a is undefined.

answered on Stack Overflow Sep 19, 2019 by Rokas Višinskas • edited Sep 19, 2019 by Rokas Višinskas

User contributions licensed under CC BY-SA 3.0