Hey,
I have got the following code:
Code:
/* Adds a move string to a MOVE_DATA * If there is no more space left, space of the MOVE_DATA will be doubled.
* Returns 1, if successful
* Returns 0, OutOfMemoryException
*/
char add_move_to_data(MOVE_DATA* move_info, char* move){
if(move_info->array_size == move_info->used_array_size){
printMoves(move_info->moves, move_info->used_array_size, 0);
printf("\n");
char* p= realloc(move_info->moves, 2*(move_info->array_size));
move_info->array_size = 2*(move_info->array_size);
if(!p){
return 0;
} else {
move_info->moves = (char**)p;
}
printMoves(move_info->moves, move_info->used_array_size, 0);
}
move_info->moves[move_info->used_array_size++] = move;
return 1;
}
With the strcuture:
Code:
typedef struct { char** moves;
size_t array_size;
size_t used_array_size;
} MOVE_DATA;
After reallocating the char**, there is only a small amount of the moves printable:
Before:
Move: 009,017,000,
Move: 010,018,000,
Move: 011,019,000,
Move: 012,020,000,
Move: 013,021,000,
Move: 014,022,000,
Move: 014,023,000,
Move: 016,024,000,
Move: 016,032,000,
Move: 016,040,000,
Move: 016,048,000,
Move: 016,017,000,
Move: 016,018,000,
Move: 016,019,000,
Move: 016,020,000,
Move: 016,021,000,
Move: 016,022,000,
Move: 016,023,000,
Move: 063,055,000,
After:
Move: 009,017,000,
Move: 010,018,000,
Move: 011,019,000,
Move: 012,020,000,
Move: 013,021,000,
Why does the realloc behave that way?
Solution:
Remember that realloc (just as malloc) requires the size in bytes, not number of "elements". –