Need help with arrays, pointers, objects

Hello everyone, I just joined the forums and I'm glad to see there is a specialized community that knows more than me about C++.
I'll get straight to the point and I don't want to appear rude . I'm not here to just ask and then leave :).

I'm making a small game engine in OpenGL, and the issue seems related to objects, arrays and pointers.

Basically I have the following global array:

Entity **entityList = new Entity*[ MAX_ENTITIES ];

and whenever I have it outside of main, it crashes the program. Let's be more specific.


If I compile something like this and run it, it will work just fine without problems:

1
2
3
4
5
6
7
8
9
10
11
int main (int argc, char *argv[])
{

    CubeSolid c1 (r1,r2,r3,r4,r5,r6,true,true);
    Entity *e1;
    e1 = new Entity(c1,ENTITY_DYNAMIC_TYPE);
    entityList[0]=e1;


}



Now, If i wanted to do the same by calling a function with the same block of code in its body, and then call one of Entity methods outside main, it will crash the program.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

void createEntity()
{


    CubeSolid c1 (r1,r2,r3,r4,r5,r6,true,true);
    Entity *e1;
    e1 = new Entity(c1,ENTITY_DYNAMIC_TYPE);
    entityList[0]=e1;
}

int main (int argc, char *argv[])
{
  createEntity(); //  THIS CRASHES THE PROGRAM WHENEVER ONE OF ENTITY METHODS IS USED OUTSIDE MAIN


}




As you can see, the program only crashes when the assignment to entityList gets done within createEntity() and a member function of an Entity object gets called. Read below for some examples.


I've tried almost anything: at first, I just had an array of pointers rather than pointers of pointers, still the same problem. I also had tried both dynamic and static memory allocations. No success, same problem.
Just why wouldn't it work when inside a function? What's the big deal with that? I know, I'm not thinking low-level enough, still It's my first , real experience with C++.



I also wanted to post more relevant code, the class headers for instance:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// THIS IS Entity.h
class Entity
{
    public:
        Entity();
        Entity(PrimitiveSolid &b,int t);
        Entity(const Entity &e);
        //Entity& operator=(const Entity& e);
        PrimitiveSolid* body;
        int type;
        void spawn(bool status);
        void setVelocity(GLfloat vX, GLfloat vY, GLfloat vZ);
        void moveTo(GLfloat x, GLfloat y, GLfloat z, GLfloat speed);
        void getPosition(GLfloat &x, GLfloat &y, GLfloat &z);
        bool isInRangeOfPoint(GLfloat range, GLfloat x, GLfloat y, GLfloat z);
        bool isSpawned();
        virtual ~Entity();
    protected:
    private:
        bool spawned;
};


// THIS IS PrimitiveSolid.h

class PrimitiveSolid
{
    public:
        PrimitiveSolid();

        bool visible;
        bool wireMode;
        virtual void draw();
        virtual void arrangeShape();
        virtual void setScale(GLfloat scale);
        virtual void setPos(GLfloat cX, GLfloat cY, GLfloat cZ);
        virtual void rotate(GLfloat rX, GLfloat rY, GLfloat rZ);
        virtual void rotateDeg(GLfloat angleX, GLfloat angleY, GLfloat angleZ);
        virtual GLfloat getScale();
        virtual GLfloat getPosX();
        virtual GLfloat getPosY();
        virtual GLfloat getPosZ();

        virtual ~PrimitiveSolid();
    protected:
    private:
};

class CubeSolid : public PrimitiveSolid
{
    public:
        CubeSolid(Rectshape &r1, Rectshape &r2, Rectshape &r3, Rectshape &r4,Rectshape &r5, Rectshape &r6,bool hidden, bool wireMode);
        CubeSolid(GLfloat size,bool hidden, bool wireMode);
        Rectshape* faces[6];

        void draw();
        void arrangeShape();
        void setScale(GLfloat scale);
        void setPos(GLfloat cX, GLfloat cY, GLfloat cZ);
        void rotate(GLfloat rX, GLfloat rY, GLfloat rZ);
        void rotateDeg(GLfloat angleX, GLfloat angleY, GLfloat angleZ);
        GLfloat getScale();
        GLfloat getPosX();
        GLfloat getPosY();
        GLfloat getPosZ();
        virtual ~CubeSolid();
    protected:
    private:
        GLfloat scale;
        GLfloat oPos[3];
};




I've also noticed that the program crashes when a function gets called by accessing a member function of the body member.

 
entityList[0]->body->draw();


But it doesn't seem to crash when I access a member variable:

entityList[0]->body->visible;



Again, all of this happens only when the assignment takes place within createEntity() or any other function as far as I know. When the assignment gets done in main, the program never crashes.

Something else worth noting: It doesn't seem to crash at all when the methods are called inside main. Again, this seems to be some kind of scope problem.
Also, since I have Visual Studio installed (but currently, I'm not using it to program), whenever the application encounters a runtime error the debugger opens and it tells me "access violation". Now I'm not sure that 's an error with the debugger or the runtime error that was encountered as I'm not familiar with visual studio.
I'm currently using MINGW and codeblocks.

The problem doesn't seem to be in the Entity class, it's the member body that causes problems with its methods.
For instance, the call entityList[0]->isSpawned(); won't crash the program, because it has nothing to do with "body". But anything related to body crashes the whole thing.

Thanks for any advice or help I can get, please do help on the current issue, the style I've adopted for my project isn't an issue I wish to address now, but any help related to the problem addressed here will be appreciated!

Thank you.
Last edited on
Where is the pointer 'body' in the Entity class initialised?

Assuming its set to the address of the reference argument b in the entity constructor then that looks like your problem
In the function createEntity() you would then be setting this pointer to the address of the local variable c1
However, this variable only exists within this function body

If you have a pointer to something in your class than you need to create what its pointing to on the heap
If you change the constructor to Entity(PrimitiveSolid *b, int t);
then in your createEntity() function use e1 = new Entity(new CubeSolid(r1,r2,r3,r4,r5,r6,true,true),ENTITY_DYNAMIC_TYPE);
that will create a pointer to your PrimitiveSolid on the heap and put it into the Entity object

You got away with it in main since there the local variable c1 lasts until the end of the program!

Note: where you have pointers like this in classes you have to write "the big three" : copy constructor, destructor and assignment operator otherwise you will get memory leaks (smart pointers are a better option)
Multi dimensional arrays are evil. Globals are also evil. A global multi dimensional array that is dynamically allocated is the devil. Also, I assume ENTITY_DYNAMIC_TYPE is a flag that distincts one form of entities from another? If so, remove that flag from the entity class, make the class abstract and write subclasses that implement the behavior of a static and dynamic entity - when your class has some state based behavior this is a dead giveaway that you want to use polymorphism.

Use a debugger and figure out where exactly the crash occurs, please.
Last edited on
Thanks, your help was quite useful. Stupid me. I thought as pointed variables as something persistent in memory for some reason, I'm obviously unfocused. Thanks again I bet that's the problem, I still have to redesign the program but it seems like the right path.

Also @hanst99: would you suggest to remove the flag even if the latter was used only to include them in the threading process due to the fact that dynamic entities will move (and i'm using threads for that) while static ones don't, that's basically the difference between the two types.
Last edited on
fact that dynamic entities will move (and i'm using threads for that)


I can't imagine this going well. I suppose this is for a game? The only reason I can think of why you'd do that is if you had some really expensive path finding algorithm and you wanted to perform the calculations for the next "logic step" while drawing the current one. And then you'd only use a single thread (well, next to the main one), it kinda sounds to me as if you'd have planned to create a thread for every single moving object.
Last edited on
Only the ones that move at different speeds, considering at most 3-4 different speeds or so.
Yes it's going to be a game. Now that we started talking about this, what would be a nice way to handle this rather than using threads? When I used to make simple games in python I would increase the movement each frame so that the speed would have been greater.
But that causes some issues, for example, some objects might just be out of reach and never collide with each other as due to movement increment not being a multiple of some other object's increment. I don't know if I made myself clear on this... so I thought that maybe using different delays between each frame for each game entity might have been a good solution (using a Sleep(delay) for each thread), if not, what else could I do to solve this issue? Thanks.
Last edited on
Use frame based logic.

For example, you set up a constant (logical) fps rate of 60 FPS with a timer (how exactly depends on what API you are using) - that means 60 logic "steps" are executed each second.

Now for linear movement, you can just give each object a speed vector (2D or 3D, depending on what kind of game you have):

1
2
3
Object myObject;
myObject.setSpeed(Vector3D(1,0,0)/60.0f); /*this means that at an fps rate of 60
                                         the object moves 1 unit on the x axis per second*/


How exactly you handle stuff depends on what kind of game you're actually trying to make, but frame based logic is basically always the way to go (some people apparently like to do it with time difference - a pretty shitty idea if you ask me because there are many kinds of behaviors that won't work for variable time between each step - for example, collision detection (except if your collision detection is a priori, but that's usually unnecessarily complicated), AI etc etc).
Thanks very much. I believe I see your point... I'll try that.
May I ask you something else?
Basically, I'm making the engine with the following classes:
Point
Line
Rectangle
Solid (parent)
- Cube (subclass)
Entity


Now, it works like this:
Entity->Cube->Rectangle->Line->Point
a solid needs faces that are made of rectangles, which are made of lines, which are made of two points.

This seemed as a fairly nice way to handle things as I can easily handle , change, manage, edit, set every part of a cube.
Rotation, motion etc are all based on points and every function goes up to the solids. So every point "influences" what is going on in their upper level.
I got a problem with this approach though:
1) is this a nice / convenient / efficient way to do it?
2) if not, what would be a better way to handle things given my necessity of handling each aspect of the solid independently ?
3)
I made a constructor for entity and every other class that look like this:

Entity::Entity(GLfloat size)
{
body = new CubeSolid(1.0,false,false);
spawned = false;
}

CubeSolid::CubeSolid(GLfloat size,bool hidden, bool wireMode) : PrimitiveSolid()
{

faces[0] = new Rectshape(1.0,false);
faces[1] = new Rectshape(1.0,false);
faces[2] = new Rectshape(1.0,false);
faces[3] = new Rectshape(1.0,false);
faces[4] = new Rectshape(1.0,false);
faces[5] = new Rectshape(1.0,false);


//// IRRELEVANT CODE ////
}

Rectshape::Rectshape(GLfloat size,bool hidden)
{
this->_topside = new Line(size,false);
this->_rightside = new Line(size,false);
this->_bottomside = new Line(size,false);
this->_leftside = new Line(size,false);

//// IRRELEVANT CODE ////

}

Line::Line(GLfloat size, bool hidden)
{
point1 = new Point(1.0,1.0,1.0,true);
point2 = new Point(1.0,1.0,1.0,true);


//// IRRELEVANT CODE ////
}

Point::Point(GLfloat x, GLfloat y, GLfloat z,bool hidden)
{
pos[0] = x;
pos[1] = y;
pos[2] = z;
oPos[0]=x;oPos[1]=y;oPos[2];
visible = !hidden;
}
With this approach I can easily create an entity and the constructors will do the rest since I have a function that automatically arranges points, rectangles, lines in a solid shape, no matter how far apart or how they're located in the space. I can access the solid class from Entity, has body is a solid object. But in order to access the rectangles that make up the solid, I need to do that thru the cube class directly! But I get uninitialized member variables and crashes when i call member functions that go beyond the solid class ( like rectangles).

For example, if I have the Entity class with body inside it, body is a pointer to a solid object (a cube in this case).
Though I can easily access the solid from a pointer to entity, I cannot seem to access the rectangles of which body is made of. I cannot seem to do this:

entityList[0]->body->faces[0]->function();

So how would I solve this problem?




Last edited on
1
2
3
4
5

this->_topside = new Line(size,false);
this->_rightside = new Line(size,false);
this->_bottomside = new Line(size,false);
this->_leftside = new Line(size,false);


This isn't java. Members should be objects, not pointers unless you need polymorphy or dynamic allocation makes sense for other reasons (linked list or something). Neither is true for your lines etc.


Though I can easily access the solid from a pointer to entity, I cannot seem to access the rectangles of which body is made of. I cannot seem to do this:

entityList[0]->body->faces[0]->function();


You are probably allocating something wrong somewhere - but the underlying issue isn't that this doesn't work, but that you're trying to do it in the first place! If you need to do this, it indicates a flaw in design - objects should manage themselves.
Topic archived. No new replies allowed.