0

I'm trying to build a simple tournament in c, but I'm struggling to use a multidimensional array of struct round.

typedef struct round{
   enum role  myrole;
   int *opponent;
   int flag;
} *round_t;

static round_t** rounds;

void buildTournament(int players){
   int roundCount = ceil_log2(players);

   rounds = malloc( players * sizeof *rounds );

   size_t row;
   for (row = 0; row < roundCount; ++row)
       rounds[row] = malloc( roundCount * sizeof **rounds );

   int i;
   for (i = 0; i < players; i++)
   {
        for (k = 0; k <= roundCount; k++)
        {
            round_t round = malloc(sizeof(round_t));
            if(i % 2 == 0)
            {
                round->myrole = WINNER;
            }
            else
            {
                round ->myrole = LOSER;
            }
            rounds[i][k] = round;
        }
   }

}

With 8 players, it throws a seg fault writing to rounds[3][0], which is the 10th memory location. This makes me think I'm only allocating 9 memory locations to the array. Obviously, I'm new to C, so any help would be very appreciated.

2
  • 1
    for (k = 0; k <= roundCount; k++) should be k < roundCount otherwise you index out of bounds for rounds[i][k] Commented Feb 28, 2015 at 19:29
  • Thanks, I changed my original implementation which started k at 1 and used rounds[i][k-1] for a simpler explanation for SO. Commented Feb 28, 2015 at 19:58

1 Answer 1

1

You are not allocating enough space here

round_t round = malloc(sizeof(round_t));

your fault is that you declared round_t as a pointer to a struct round which hides the fact that round_t is struct round * from you, hence sizeof(round_t) seemed natural but it's wrong because it's allocating space for a pointer, and not for a strcut, change it like this

round_t round = malloc(sizeof(*round));

or

round_t round = malloc(sizeof(struct round));

Don't typedef pointers it makes your code very confusing, and if you must typedef a pointer, try to imply that it is a pointer in it's name, something like

typedef struct round{
    enum role  myrole;
    int *opponent;
    int flag;
} round_t;
typedef round_t *round_p;

and also, as @rpattiso commented, you should fix the for loop condition.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.