I am trying to transpose a 2D char array (in C) of unknown size rows and columns at run time. I use malloc to create the array and for loops to copy the chars form the original array to the new array. I am testing on a sample array of size 9x15 to create an array of 15x9 and the code works until my outer loop i =11 and then crash. In debug mode it shows Exception: Access violation writing to location 0xcdcdcdcd. The original array is read in from a file and is created using the same malloc code and works just fine. I have tried moving the code to main, but get the same exception. I am confused on how it does not create the array properly and would appreciate some input on how to correct the code or trouble shoot the issue better. My code is here
char **dest_grid = malloc(sizeof(char*) * source_col);
if (dest_grid == NULL) {
printf("Memory not assigned\n");
exit(EXIT_FAILURE);
}
else {
for (i = 0; i <= source_row; i++) {
dest_grid[i] = malloc(sizeof(char) * source_row);
}
for (i = 0; i < source_col; i++) {
for (j = 0; j < source_row; j++) {
if (j == source_row) {
dest_grid[i][j] = '\0';
}
else {
dest_grid[i][j] = source_grid[j][i];
}
}
}
}
for (i = 0; i < source_col; i++) {
free(dest_grid[i]);
}
free(dest_grid);
edit: The size of the array is provided from the file when read into memory. Multiple arrays are read in from the file of various sizes.