显然,因为它的段错误,C++编译器不会输出任何东西?我在写一些C++代码时遇到了一些麻烦。我是一个新手,我一直在寻找这段时间现在...我无法弄清楚。如何调试C++ segfault?
我最好的猜测是它在Deck()构造函数中的某个地方,任何人都可以给我一只手?
任何帮助,将不胜感激!
谢谢!
跟进:未来,有没有人有任何调试segfaults的好方法?
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;
}
你用调试器通过代码?这通常可以帮助很多...输出语句的存在表明你依靠它们来告诉你代码执行得有多远。学习使用你的调试器。 – Steve
*调试帮助请* ---使用GDB ... –
当日有用的事实:像gdb这样的调试器可以告诉你发生段错误的确切位置+回溯,而像valgrind这样的工具有时可以告诉你更多信息。你应该学习如何使用它们。 –