如何调试C ++段错误?

时间:2015-10-06 22:39:55

标签: c++ segmentation-fault

显然,由于它是一个段错误,C ++编译器不会输出任何东西?我在写一些C ++代码时遇到了一些麻烦。我是一个新手,我一直在寻找这个段错误......我无法弄清楚。

我最好的猜测是它在Deck()构造函数中的某个地方,任何人都可以帮我一把吗?

任何帮助将不胜感激!

谢谢!

跟进:将来,有没有人有任何调试段错误的好方法?

Deck.cpp

#include "Deck.h"

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using std::ostream;
using std::vector;

const string Deck::RANKS[13] = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
const string Deck::SUITS[4] = {"H","D","C","S"};
string cards[52];
int card = 0;


Deck::Deck() : size(0)
{
    for (int i = 0; i < 13; i++)
    {
        for (int j = 0; j < 4; j++)
        {
            cards[size] = RANKS[i] + SUITS[j];
            size++;
        }
    }

    shuffle();
}

Deck::~Deck() {}

void Deck::shuffle()
{
    size = MAX_SIZE;
    std::random_shuffle(&cards[0], &cards[MAX_SIZE-1]);
}

string Deck::getCard()
{
    card++;
    return cards[card-1];
}

加入deck.h

#ifndef DECK_H
#define DECK_H


#include <ostream>
#include <string>
#include <vector>
using std::ostream;
using std::string;
using std::vector;

class Deck
{
private:
    static const int MAX_SIZE = 52;
    static const string RANKS[13];
    static const string SUITS[4];
    static const string DECK[52];

    int size;


public:
    Deck();
    ~Deck();
    void shuffle();
    string getCard();
    int getDeckSize() const {return size;}
    friend ostream& operator<<(ostream&, const Deck&);
};

#endif

Main.cpp的

#include <iostream>
#include "Deck.h"
using namespace std;

int main()
{


   int pairs = 0;

   for(int x = 0; x < 100; x++)
   {
       cout << "yep";

       Deck deck;
       cout << "awooga";

       deck.shuffle();
       cout << "hai";

       string cards[2];

       cards[0] = deck.getCard();
       cards[1] = deck.getCard();

       for(int y = 0; y < 5; y++)
       {
           string tempCard = deck.getCard();
           if(cards[0].compare(tempCard) == 0 || cards[1].compare(tempCard) == 0)
           {
              pairs++;     
           }
       }
   }


   cout << pairs;

   return 0;
}

1 个答案:

答案 0 :(得分:5)

您的问题是getCard有副作用,每次调用时都会增加card的值。一旦你调用它超过52次,你的程序可能会崩溃。请注意,card是一个全局变量,并且在您创建新套牌时不会重置为零。

我还注意到您对random_shuffle的调用有一个错误。结束迭代器需要超出容器的实际末端,而不是将指向结束(因此它是半开放范围)。

最后,为了调试一般的分段错误,在系统上启用核心转储,并使用gdb将核心附加到二进制文件。这有时会给你一个很好的线索从哪里开始。

相关问题