Reputation: 5592
I can't truly understand why the free process returns in an error. I got this code in C:
int LuffarschackStart(void)
{
/* to avoid the program from closing */
char readEnd;
int i = 0;
board_type *board = malloc(sizeof(square_type));
if (board == NULL)
{
printf("Could not allocate the memory needed...");
scanf("%c", &readEnd);
return 0;
}
for(i = 0; i < 9; i = i + 1)
board->square[i].piece_type = NO_PIECE;
board_play_game(board);
free(board);
printf("Press any key and enter to quit the program...");
scanf("%c", &readEnd);
return 0;
}
The board struct that i am allocating looks like this:
typedef struct
{
/* flag to indicate if a square is free or not */
int free;
/* the type of piece stored on the square if the
square is not free, in this case the admissible
values are CROSS_PIECE and CIRCLE_PIECE,
otherwise the value NO_PIECE is used */
int piece_type;
} square_type;
typedef struct
{
square_type square[N_SQUARES];
int computer_type;
int player_type;
} board_type;
Could the problem be that i need to free the square_type inside the board first? If thats the case, how do i free that?
Upvotes: 3
Views: 624
Reputation: 1831
Another nitpick, nothing to do with your memory problem: you probably don't need an extra flag to mark free squares if you already distinguish between the three possible pieces CROSS / CIRCLE / NONE...
Upvotes: 0
Reputation: 76611
Others have already pointed out the error, but here's a macro that will help catch those errors:
#define NEW(type) (type *)malloc(sizeof(type))
You would then use it like this:
// Correct usage
board_type *board = NEW(board_type);
What nice about this is that if you make a mistake like you did, you should get a compiler warning about mismatched pointers due to the cast inside the macro:
// Incorrect usage, a decent compiler will issue a warning
board_type *board = NEW(square_type);
Upvotes: 3
Reputation: 8258
First, you are allocating the wrong size here:
board_type *board = malloc(sizeof(square_type));
It needs to be
board_type *board = malloc(sizeof(board_type));
You probably didn't saw this problem, but I suspect you are writing to unallocated memory. (Potential memory exception).
You don't need to free the inner array, because it is a fixed size array, and when you allocate a board_type, it will be ready with the entire array.
Fix the malloc, it will solve the free.
Upvotes: 2
Reputation: 29174
I think your malloc is wrong. It should be
board_type *board = malloc(sizeof(board_type)); /* instead of sizeof(square_type) ...*/
Besides this I think your code is correct ...
Upvotes: 7