Good day, help solve the problem: There is a hierarchy of classes CBullet -> CSplashBullet -> CFireBullet. There is a function that returns a pointer to the base (CBullet) class:

CBullet* CTower::fireInTheHole(DRAQON* target, SDL_Texture* tex) { switch (this->type) { case TOWER_FIRE: SDL_Rect tempRect; tempRect.x = 0; tempRect.y = 0; tempRect.w = 32; tempRect.h = 32; return &CFireBullet(tex, this->x, this->y, 10, 1, &tempRect, target, this->splash); break; } } 

further in the main function:

 std::cout << "close1" << std::endl; CBullet* testBullet = towerIterator->fireInTheHole(&draqotest, bulletTexture); CBullet** ptrptr = &testBullet; testBullet->fly(); std::cout << "close1-2" << std::endl; (*ptrptr)->fly(); std::cout << "close2" << std::endl; 

testBullet-> fly (); it is caused normally. "close1-2" is output, and on (* ptrptr) -> fly (); prog crash.

here is a description of the fly () method itself

 void CFireBullet::fly() { std::cout << "CFireBullet::fly" << std::endl; double angle = atan2(target->y - this->y, target->x - this->x); this->x += cos(angle) * this->speed; this->y += sin(angle) * this->speed; } 

Why do I need a pointer to a pointer? The fact is that I have a list <CBullet *> and when I try to access an object through an iterator (which, in fact, is a pointer to a pointer to an object), exactly the same crash occurs.

    1 answer 1

    First, in CTower::fireInTheHole you return a pointer to a dead CFireBullet object. Welcome to the world of memory corruption! This should be the root problem.

    The fact is that the code

     &CFireBullet(tex, this->x, this->y, 10, 1, &tempRect, target, this->splash) 

    creates a temporary object that will die when the line runs. Do not do this, use honest new . Remember to release the object when you no longer need it.

    • Thank! It seems that it solved the problem (in any case, the prog ceased to crash, though it does not perform all the functionality that was needed). I don’t have time to debug now, so I’ll just ask for the future: how can I clear the list with these pointers to the base class? if memory is not allocated anywhere within the classes themselves, then the following method is suitable: for (bulletIterator = bullet_list.begin (); bulletIterator! = bullet_list.end (); bulletIterator ++) {delete (* bulletIterator); } ?? - melodicwing 2:58 pm
    • @melodicwing: Yes, it will. It is conceptually more correct, however, to use shared_ptr and the like: they will delete the object automatically. - VladD