SDL_FreeSurface crashing?

I’m trying to write a simple card game using SDL. At the end of the
game I free the surfaces used for the cards like this:

void remCards(){
int i;
for(i = 0; i < 52; i++){
if(deck[i].img != NULL){ // Just a safety check

The program crashes (SDL_Parachute) every time this method is called.
The crashes happen for a different value of i each time also. I’m
assuming this means that I’m trying to free memory that I shouldn’t be?

The only place that I think I might be messing this up is when I shuffle
the deck. The card struct looks like this:

struct card {
int value;
SDL_Surface *img;
int suit;

To shuffle the deck I have an (global) array of cards in order:

struct card deck[52];

I then create another array:

struct card shuffled[52];

I then randomly move cards from the ordered deck to the shuffled deck
like this:

shuffled[j].suit = deck[i].suit;
shuffled[j].value = deck[i].value;
shuffled[j].img = deck[i].img;

I then move the cards back to the original global deck.

Is there a problem with they way I’m assigning the images? If not, what
else could cause the Seg Fault?


I think when you shufle the deck you put multiple cards in one place
thus overwriting the previous values. So your deck is not a real deck,
because there are multiple instances of some cards. Now when you free
the cards the first card that is more than one time in the deck is
tried to free two or more times.

Easiest way to repair is to use this kind of shufle.

#define YOUR_SHUFLE_TIMES 1000 // This value determines the amount of
random swaps 1000 swaps gives you pretty random deck

int i;
struct card t,*a,*b;

for (i=0; i<YOUR_SHUFLE_TIMES; i++) {

t.suit = a->suit;
t.value = a->value;
t.img = a->img;

a->suit = b->suit;
a->value = b->value;
a->img = b->img;

b->suit = t.suit;
b->value = t.value;
b->img = t.img;

Even easier would be to use a new shufled deck as array of pointers. So
the swapping would be only swapping pointers and the original deck
would be in order all the time you would simply give the shufled decks
card a pointer from the deck array and then shufle the game deck usign
similar loop than the above.