Fratel Fratel - 23 days ago 6
C Question

Strange behavior while filling dinamically allocated 2D char array in C

I need to create a program that plays the game Hex on a 14x14 board.
So I created, allocated and filled the board with '-' (our pattern for empty spaces).

When I try to print the board's coordinates, I don't always get '-' but some random characters.

Also, if I try to printf array[i][j] on the createBoard function after the line "board[i][j] = '-';" I get a segmentation fault right after it prints tab[8][0].

What is causing this and how can I fix it?

My code:

#include <stdio.h>
#include <stdlib.h>
char **createBoard()
{
/*Allocates a 14x14 matrix and fills it
*with '-' to create the board.*/
int i, j;
char **board;
board = malloc(14);
if (!board) exit(1);
for (i = 0; i < 14; i++){
board[i] = malloc(14);
if (!board[i]) exit (1);
for (j = 0; j < 14; j++)
board[i][j] = '-';
}
return board;
}


int main()
{
int i, j;
char **board = createBoard();
for (i = 0; i < 14; i++)
for (j = 0; j < 14; j++)
printf("tab[%d][%d]: %c\n",i, j, board[i][j]);
return 0;
}

Answer

For starters it is not clear why you don't want to declare an array instead of allocating dynamically numerous one-dimensional arrays.

As for the code then this memory allocation

board = malloc(14);

is invalid. You have to write

board = malloc( 14 * sizeof( char * ));

Also you should free all the allocated memory in the reverse order relative to its allocation before the program ends.

Take into account that it is always better to use named constants instead of magic numbers. At least you could write either

#define N 14

before main

or

const int N = 14.

and use the variable N everywhere where you are using magic number 14.

By the way according to the C Standard function main without parameters shall be declared like

int main( void )