I have built a game of tic tac toe for Uni assigment but the catch is that the board can be any size of NxN. My program works totally fine when the dimensions are 3x3 or 4x4 but when I try to build a board bigger than that size I get error code -1073741819 (0xC0000005). I tried to read on the topic but I can't understand what is the problem. Here is my code for building the 2D array:
void buildBoard(char ***board, int size)
{
int i;
*board=(char**)malloc(size*sizeof(char));
if(board==NULL)
{
printf("Allocation failed!\n");
exit(1);
}
for(i=0;i<size;i )
{
(*board)[i]=(char*)malloc(size*sizeof(char));
if((*board)[i]==NULL)
{
printf("Allocation failed!\n");
exit(1);
}
}
}
Also, if there's a need for me to post to full code in order to find the problem I will gladly post the full version.
CodePudding user response:
You are allocating space for size
number of char
s here:
*board=(char**)malloc(size*sizeof(char));
What you should do is to allocate size
number of the things *board
should point at:
*board = malloc(size * sizeof **board);
An alternative that would be simpler is to only do one allocation and to cast the return value to a pointer to the first element in an array of size
elements of char[size]
.
VariableType(*first_row_pointer)[COLS] = malloc(sizeof(VariableType[ROWS][COLS]));
It'll have the benefit of less pointer indirections and less memory allocated - and you'll also only need one free
to release the acquired memory.
Example:
#include <stdio.h>
#include <stdlib.h>
void *buildBoard(size_t size) {
// calloc to zero the allocated memory:
void *rv = calloc(/*rows*/size, sizeof(char[/*columns*/size]));
if(rv == NULL) {
perror("calloc");
exit(EXIT_FAILURE);
}
return rv;
}
int main() {
size_t size = 10;
// cast to a pointer to the first row in the allocated 2D array:
char(*board)[/*columns*/size] = buildBoard(size);
// then use `board` like a regular array:
for(size_t row = 0; row < size; row) {
for(size_t col = 0; col < size; col) {
printf("%d ", board[row][col]);
}
putchar('\n');
}
free(board); // only one free
}
CodePudding user response:
Code's allocation is too small as the wrong type is used.
// malloc(size*sizeof(char));
malloc(size*sizeof(char *));
Reducing the number of *
in code helps to see this and avoid the problem.
Allocating to the referenced object is easier to code right, review and maintain than allocating to the size of the type.
ptr = malloc(sizeof ptr[0] * n)
void buildBoard(char ***board, int size) {
if (board && size > 0) {
char **b = malloc(sizeof b[0] * size);
if (b == NULL) {
fprintf(stderr, "Allocation failed!\n");
exit(1);
}
for (int i = 0; i < size; i ) {
b[i] = malloc(sizeof b[i][0] * size);
if(b[i] == NULL) {
fprintf(stderr, "Allocation failed!\n");
exit(1);
}
}
*board = b;
}
}