顯然,因爲它的段錯誤,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這樣的工具有時可以告訴你更多信息。你應該學習如何使用它們。 –