Inability to free memory

I cannot understand why the free process returns with 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 structure of the board that I distribute 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 square_type inside the board first? If so, how should I free it?

+3
source share
4 answers

I think your malloc is wrong. It should be

board_type *board = malloc(sizeof(board_type)); /* instead of sizeof(square_type) ...*/

Also, I think your code is correct ...

+7
source

Others have already pointed out the error, but here is a macro to help catch these errors:

#define NEW(type)   (type *)malloc(sizeof(type))

Then you will use it as follows:

// Correct usage
board_type *board = NEW(board_type);

, , , - :

// Incorrect usage, a decent compiler will issue a warning
board_type *board = NEW(square_type);
+3

:

board_type *board = malloc(sizeof(square_type));

board_type *board = malloc(sizeof(board_type));

, , , . ( ).

, , board_type, .

malloc, .

+2

, : , , , , CROSS/CIRCLE/NONE...

0

Source: https://habr.com/ru/post/1732688/


All Articles