Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with Pointers (Only in Release Build)

unsure how to go about describing this but here i go:

For some reason, when trying to create a release build version of my game to test, the enemy creation aspect of it isn't working.

Enemies *e_level1[3];
e_level1[0] = &Enemies(sdlLib, 500, 2, 3, 128, -250, 32, 32, 0, 1);
e_level1[1] = &Enemies(sdlLib, 500, 2, 3, 128, -325, 32, 32, 3, 1);
e_level1[2] = &Enemies(sdlLib, 500, 2, 3, 128, -550, 32, 32, 1, 1);

Thats how i'm creating my enemies. Works fine when in the debug configuration but when i switch to the release config, it doesn't seem to initialize the enemies correctly.

To me, this seems a bit strange that it works in debug but not in release, any help appreciated on what mostly is what i've done wrong.

like image 372
Danran Avatar asked Jun 24 '26 05:06

Danran


2 Answers

e_level1[0] = &Enemies(sdlLib, 500, 2, 3, 128, -250, 32, 32, 0, 1);

doesn't do what you think it does. If it is the constructor call, it creates a temporary and its address is stored in e_level1[0]. When e_level1[1] is initialized e_level1[0] destructor is probably already called.

You probably want to do

Enemies* e_level1[3] = 
    {
        new Enemies(sdlLib, 500, 2, 3, 128, -250, 32, 32, 0, 1) , 
        new Enemies(sdlLib, 500, 2, 3, 128, -325, 32, 32, 3, 1) , 
        new Enemies(sdlLib, 500, 2, 3, 128, -550, 32, 32, 1, 1)
    };
like image 54
parapura rajkumar Avatar answered Jun 26 '26 19:06

parapura rajkumar


Other people have already pointed out the error, namely that the temporaries are getting destroyed straight away, but all of the answers so far are using manual memory management - it's more idiomatic in C++ to use e.g. std::vector for something like this, e.g.

std::vector<Enemies> enemies;
enemies.push_back(Enemies(sdlLib, 500, 2, 3, 128, -250, 32, 32, 0, 1));
enemies.push_back(Enemies(sdlLib, 500, 2, 3, 128, -325, 32, 32, 3, 1));
enemies.push_back(Enemies(sdlLib, 500, 2, 3, 128, -550, 32, 32, 1, 1));

Then you just access the Enemies instances as enemies[0] through enemies[2] and they get cleaned up automatically when the vector goes out of scope.

like image 31
Stuart Golodetz Avatar answered Jun 26 '26 20:06

Stuart Golodetz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!