简体   繁体   中英

Segmentation Fault (Core Dumped) - Pointers

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)

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM