繁体   English   中英

递归函数中的shared_ptr分配导致分段错误

[英]shared_ptr assignment in recursive function causing Segmentation Fault

提前道歉,发布了如此多的代码...

我正在构建一个类似“多米诺骨牌”游戏的模拟游戏,该游戏称为“鸡脚”,玩家将“骨头”从骨头堆中抽到手中,然后在场地上玩多米诺骨牌。

这是我尝试使用智能指针的第一个程序,但遇到了一个我似乎无法查明原因的问题。 偶尔运行该程序会给我带来细分错误。 可以在下面看到gdb堆栈跟踪。

奇怪的shared_ptr行为,此答案表明这可能与递归函数有关。

我在这里做错了什么? 另外,如果我滥用了这些shared_ptr实例中的任何一个或可以改善实现,那么任何建议都将不胜感激-谢谢!

ChickenFoot.cpp

#include <iostream>
#include <cstdlib>
#include <ctime>
#include "Game.h"

const int NUM_OF_PLAYERS = 4;

int main(int argc, char** argv) {
    std::srand(std::time(0));

    Game* chickenfoot = new Game(NUM_OF_PLAYERS);
    chickenfoot->start(DOMINOES_SET_SIZE);

    delete chickenfoot;

    return 0;
}

Game.h

#include <memory>
#include <vector>
#include "Boneyard.h"
#include "Player.h"
#include "Field.h"

const int INITIAL_HAND_SIZE = 7;
static const int DOMINOES_SET_SIZE = 9;

const bool DEBUG = false;

class Game {
private:
    std::vector< std::shared_ptr<Player> > players;
    std::shared_ptr<Boneyard> boneyard;
    bool played_rounds[DOMINOES_SET_SIZE]; // This will keep track of which double rounds have already been played

    int getHighestUnplayedRound(bool* played);
    int getNextHighestUnplayedRound(bool* played, int round);
public:
    Game(int num_of_players);
    void start(int highest_double);
};

Game.cpp

#include "Game.h"
#include <iostream>

Game::Game(int num_of_players)
{
    boneyard = std::make_shared<Boneyard>();
    for (int i = 0; i < num_of_players; i++) {
        players.emplace_back(std::make_shared<Player>(i));
    }
    for (int i = 0; i <= DOMINOES_SET_SIZE; i++) {
        played_rounds[i] = false;
    }
}
void Game::start(int highest_double)
{
    if (highest_double < 0) {
        return;
    } else {
        boneyard->initialize();
        for (int i = 0; i < INITIAL_HAND_SIZE; i++) {
            for (std::vector< std::shared_ptr<Player> >::iterator j = players.begin(); j != players.end(); j++) {
                (*j)->draw(boneyard);
            }
        }
        for (std::vector< std::shared_ptr<Player> >::iterator i = players.begin(); i != players.end(); i++) {
            if ((*i)->hasDouble(highest_double)) {
                std::shared_ptr<Bone> hd_bone = (*i)->getDouble(highest_double);
                // Do something here to actually play the game...
                played_rounds[highest_double] = true;
                break;
            }
        }
    }
    for (std::vector< std::shared_ptr<Player> >::iterator i = players.begin(); i != players.end(); i++) {
        (*i)->discardAll();
    }
    if (played_rounds[highest_double]) {
        start(getHighestUnplayedRound(played_rounds));
    } else {
        start(getNextHighestUnplayedRound(played_rounds, highest_double));
    }
}

播放器

#include "Bone.h"
#include "Boneyard.h"
#include <vector>
#include <memory>

class Player {
private:
    int id;
    std::vector< std::shared_ptr<Bone> > hand;
    struct isDouble {
        int m_value;
        isDouble(int value) : m_value(value) {}
        bool operator()(const std::shared_ptr<Bone> b) const {
            return (b->getLeft() == m_value && b->isDouble());
        }
    };

public:
    Player(int id);
    void draw(std::shared_ptr<Boneyard> yard);
    std::shared_ptr<Bone> getDouble(int number);
    bool hasDouble(int number);
    void discardAll();
};

Player.cpp

#include <iostream>
#include <algorithm>
#include "Player.h"
...
std::shared_ptr<Bone> Player::getDouble(int number)
{
    auto result = std::find_if(hand.begin(), hand.end(), isDouble(number));
    if (result != hand.end()) {
        hand.erase(std::remove_if(hand.begin(), hand.end(), isDouble(number)), hand.end());
        return *result;
    }
    return nullptr;
}
bool Player::hasDouble(int number)
{
    auto result = std::find_if(hand.begin(), hand.end(), isDouble(number));
    return (result != hand.end()) ? true : false;
}
void Player::discardAll()
{
    hand.clear();
}

跟踪:

(gdb) backtrace
#0  0x0000000000401a26 in std::_Sp_counted_base<(__gnu_cxx::_Lock_policy)2>::_M_release (this=0x622d10) at /usr/include/c++/5/bits/shared_ptr_base.h:150
#1  0x0000000000401505 in std::__shared_count<(__gnu_cxx::_Lock_policy)2>::~__shared_count (this=0x7fffffffd548, __in_chrg=<optimized out>) at /usr/include/c++/5/bits/shared_ptr_base.h:659
#2  0x0000000000401368 in std::__shared_ptr<Bone, (__gnu_cxx::_Lock_policy)2>::~__shared_ptr (this=0x7fffffffd540, __in_chrg=<optimized out>) at /usr/include/c++/5/bits/shared_ptr_base.h:925
#3  0x0000000000401384 in std::shared_ptr<Bone>::~shared_ptr (this=0x7fffffffd540, __in_chrg=<optimized out>) at /usr/include/c++/5/bits/shared_ptr.h:93
#4  0x0000000000405ad4 in Game::start (this=0x622030, highest_double=6) at Game.cpp:28
#5  0x0000000000405b8b in Game::start (this=0x622030, highest_double=7) at Game.cpp:39
#6  0x0000000000405b8b in Game::start (this=0x622030, highest_double=9) at Game.cpp:39
#7  0x0000000000405b8b in Game::start (this=0x622030, highest_double=8) at Game.cpp:39
#8  0x0000000000405bb7 in Game::start (this=0x622030, highest_double=9) at Game.cpp:41
#9  0x0000000000405b8b in Game::start (this=0x622030, highest_double=4) at Game.cpp:39
#10 0x0000000000405bb7 in Game::start (this=0x622030, highest_double=5) at Game.cpp:41
#11 0x0000000000405bb7 in Game::start (this=0x622030, highest_double=6) at Game.cpp:41
#12 0x0000000000405bb7 in Game::start (this=0x622030, highest_double=7) at Game.cpp:41
#13 0x0000000000405bb7 in Game::start (this=0x622030, highest_double=8) at Game.cpp:41
#14 0x0000000000405bb7 in Game::start (this=0x622030, highest_double=9) at Game.cpp:41
#15 0x0000000000408360 in main (argc=1, argv=0x7fffffffdaf8) at ChickenFoot.cpp:14

问题在这里...

std::shared_ptr<Bone> Player::getDouble(int number)
{
    auto result = std::find_if(hand.begin(), hand.end(), isDouble(number));
    if (result != hand.end()) {
        hand.erase(std::remove_if(hand.begin(), hand.end(), isDouble(number)), hand.end());
        return *result;
    }
    return nullptr;
}

您在返回值之前先擦除了该值。 你不能那样做。 一旦调用hand.erase()result (它是一个迭代器)将失效,并且*result是垃圾。

一般而言,该功能非常令人困惑,但是我认为您正在为类似的事情而努力...

std::shared_ptr<Bone> Player::getDouble(int number)
{
    auto result_iter = std::find_if(hand.begin(), hand.end(), isDouble(number));

    if (result_iter != hand.end()) {
        // Saving the shared_ptr stops it from being released when we erase the iterator
        std::shared_ptr<Bone> result = *result_iter;

        // Remove the bone from hand
        hand.erase(result_iter);

        return result;
    }

    return nullptr;
}

让我补充我是怎么发现这一点,因为它归结为阅读堆栈跟踪。

递归调用start是可疑的,但无害。 这不是堆栈溢出错误,所以您很酷。

前4行表明您在shared_ptr的析构函数中存在错误(这意味着其数据已损坏),该行是Game.cpp:28 ,即std::shared_ptr<Bone> hd_bone = (*i)->getDouble(highest_double);之后的std::shared_ptr<Bone> hd_bone = (*i)->getDouble(highest_double);

这或多或少地保证了您的错误在getDouble ,这是一个很小的函数,您可以专注于它来查找错误。

这里的错误与Strange shared_ptr的行为无关。 在那种情况下,shared_ptr析构函数调用是递归发生的。 这不是在这里发生,其中shared_ptr析构函数仅发生一次。 这是您的shared_ptr数据损坏的简单问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM