-1

I'm new to malloc. Where am I going terribly wrong?

#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
typedef enum {RED_WINS, YELLOW_WINS, TIE, STILL_PLAYING} gamestate;
typedef enum {EMPTY, RED_COIN, YELLOW_COIN} square;

typedef struct {
    int numRows, numCols;
    int coinsInBoard;
    gamestate state;
    square** squares;
} gameboard;

gameboard* gameboard_create(int numRows, int numCols);
void gameboard_print(const gameboard board);
void gameboard_initialize(gameboard* board);

This is where I don't know what I'm doing more than anywhere.

// allocates space for the gameboard and its squares
gameboard* gameboard_create(int numRows, int numCols) {

        gameboard* result = malloc(sizeof(gameboard));
        result->squares= malloc(sizeof(square*)*numRows);
        for(int i = 0; i<numRows; i++){
            result-> squares[i] = (square*)malloc(sizeof(square)*numCols);
        }
    for (int i =0; i< result->numRows; i++){
        for(int j= 0; j< result->numCols; j++){
            
            result->squares[i][j] = EMPTY;
        }
    }
        return result;
}

// prints the coins currently in the board
void gameboard_print(const gameboard board){
    for (int i = 0; i < board.numRows; i++) {
        for (int j = 0; j < board.numCols; j++) {
            printf("* ");
        }
        printf("\n");
        }
}

int main() {
    printf("test\n");
    gameboard* result = gameboard_create(5, 5);
    gameboard_print(*result);
    return 0;
}

I'm trying to allocate enough memory for a 2D array that will play connect 4 on any size board.

Currently nothing apart from 'test' is printing

1 Answers1

0

The main problem:

You forgot to set the values of result->numRows and result->numCols. Thus, undefined behavior strikes due to the usage of a variable that has not been initialized.

Just add

result->numRows = numRows;
result->numCols = numCols;

in gameboard_create anywhere before the loops that set result->squares[i][j] to EMPTY.


Misc

  1. Don't cast the result of malloc (and family). Remove the cast from

    result-> squares[i] = (square*)malloc(sizeof(square)*numCols);
    
  2. Make a habit of freeing everything you've allocated. In the small example you show, however, memory automatically gets freed when the program ends, but it is a good practice to free memory its use.

Community
  • 1
  • 1
Spikatrix
  • 20,225
  • 7
  • 37
  • 83