Reputation: 1493
Apparently since its a segfault the C++ compiler won't output anything? I'm having some trouble with some C++ code I wrote. I'm a novice and I've been looking for this segfault for some time now... I can't figure it out.
My best guess is it is somewhere in the Deck() constructor, can anyone give me a hand?
Any help would be appreciated!
Thanks!
Follow up: In the future, does anyone have any good methods of debugging 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;
}
Upvotes: 0
Views: 1456
Reputation: 96301
Your problem is that getCard
has side effects, increasing the value of card
every time you call it. As soon as you call it more than 52 times, your program may crash. Note that card
is a global variable and doesn't reset to zero whenever you create a new deck.
I also noticed that your call to random_shuffle
has an off-by-one error. The end iterator needs to be one beyond the actual end of your container, not pointing at the end (so it's a half-open range).
Finally for debugging segmentation faults in general, enable core dumps on your system and use gdb to attach the core to your binary. That will sometimes give you a good clue where to start.
Upvotes: 5