It might be a little longer, so I'm sorry. consider the following code (I left some irrelevant parts from it). this code gets a pointer to the structure (BoardP theBoard), x and y coordinates and value. the goal is to put the value in a 2D array that is in the structure. if the coordinates are outside the borders, I need to increase the size of the table, copy the old data to the new data and put the value in its place. Well, this code works with the first call, but in the second call it fails and writes:
*** glibc detected *** ./b: double free or corruption (top): 0x092ae138 ***
I could not find the answer to it, and I hope you help.
These are calls from main ()
BoardP p = CreateNewBoard(10,10);
PutBoardSquare(p,10,5,'X');
PutBoardSquare(p,5,10,'O');
Boolean PutBoardSquare(BoardP theBoard, int X, int Y, char val) {
if (inBounds(X,Y,theBoard->_rows,theBoard->_cols)) {
theBoard->_board[X * theBoard->_cols + Y] = val;
return TRUE;
}
else {
int newRows = (X>=theBoard->_rows) ? (2*X) : theBoard->_rows;
int newCols = (Y>=theBoard->_cols) ? (2*Y) : theBoard->_cols;
BoardP newBoard = CreateNewBoard(newCols,newRows);
if (newBoard == NULL) {
return FALSE;
}
else {
copyData(theBoard,newBoard);
freeBoardArray(&theBoard->_board[0]);
theBoard->_board = newBoard->_board;
FreeBoard(newBoard);
PutBoardSquare(theBoard,X,Y,val);
return TRUE;
}
}
}
These are free functions:
void FreeBoard(BoardP board) {
if (board != NULL) {
printf("FREE 1\n");
if (board->_board != NULL) {
printf("FREE 2\n");
freeBoardArray(&board->_board[0]);
printf("FREE 3\n");
}
free(board);
}
}
static void freeBoardArray(char * arrP) {
free(arrP);
}
This is how I create a new board:
BoardP CreateNewBoard(int width, int high) {
BoardP board = (BoardP) malloc(sizeof(Board));
if (board != NULL) {
board->_board = allocateBoardArray(high,width);
if ( board->_board == NULL) {
FreeBoard(board);
return NULL;
}
initializeBoard(board,high,width,X_SIGN,SPACE);
return board;
}
else {
FreeBoard(board);
return NULL;
}
}
static char* allocateBoardArray(int row, int col) {
char* newBoard = (char*) malloc(row * col * sizeof(char));
if (newBoard == NULL) {
return NULL;
}
return newBoard;
}
this is BoardP:
typedef struct Board* BoardP;