在递归函数中的shared_ptr赋值导致分段错误

时间:2017-07-14 07:23:20

标签: c++ recursion segmentation-fault shared-ptr

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

我正在制作一个名为Chickenfoot的类似多米诺骨牌游戏的模拟游戏,其中玩家将“Bones”从boneyard中抽出来然后在场上玩多米诺骨牌。

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

Strange shared_ptr behaviour这个答案表明这可能与这是一个递归函数有关。

我在这里做错了什么?此外,如果我滥用任何这些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));
    }
}

Player.h

#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

1 个答案:

答案 0 :(得分:1)

问题出在这里......

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;
}

让我添加 我发现了这个,因为它归结为读取堆栈跟踪。

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

前4行表示您在shared_ptr的析构函数中有错误(意味着其数据在某种程度上已损坏),而行是Game.cpp:28,这是std::shared_ptr<Bone> hd_bone = (*i)->getDouble(highest_double);之后的行。

这或多或少可以保证您的错误在getDouble中,这是一个足够小的功能,您可以专注于它来查找错误。

此处的错误与Strange shared_ptr behaviour无关。在这种情况下,shared_ptr析构函数调用是递归发生的。这不会发生在这里,shared_ptr析构函数只发生一次。这是一个简单的问题,你有一个带有损坏数据的shared_ptr。