Reputation: 35
I was working on a project of an application to find the probability of winning in a game of Texas Hold'em.
My program has 3 data types given below.
typedef enum {
SPADES,
HEARTS,
DIAMONDS,
CLUBS,
NUM_SUITS
} suit_t;
struct card_tag {
unsigned value;
suit_t suit;
};
typedef struct card_tag card_t;
struct deck_tag {
card_t ** cards;
size_t n_cards;
};
typedef struct deck_tag deck_t;
I wrote a function void shuffle(deck_t * d)
which is causing a segmentation fault:
void shuffle(deck_t * d){
for (size_t i = d->n_cards-1; i >= 0; i--) {
size_t randNum = random() % n_cards;
card_t *temp = (d->cards+i);
(d->cards+i) = (d->cards+randNum);
(d->cards+randNum) = temp;
}
}
My program is being compiled. But while testing, at the point when the cards were shuffling, it said:
Segmentation Fault (Core Dumped)
Upvotes: 0
Views: 75
Reputation: 105
It fails because the variable randNum
may be bigger than n_cards - 1
which means it tries to read memory that doesn't belongs to the program (to be more exact, memory that doesn't belongs to d->cards
). So what you need to do is to ensure that:
randNum < n_cards-1
One way to do this is by:
size_t randNum = random() % (n_cards);
That way, the statment randNum < n_cards-1
will always be true
.
Upvotes: 1