Q: Printing a dynamic 2D array in C I'm trying to print a dynamic 2D array in C, the problem is that with the code it prints fine the first time but if its printed anymore times its missing the bottom row.
This is the code I'm working with: 
void display_board( int height, int width, char** gameBoard ) {
   int i;
   char *rowString;
   rowString = malloc(((width*2)+1) * sizeof( char ));
   for( i = 0; i < ((height*2) + 1); i++ ){
      rowString = *(gameBoard + i);
      printf("%s\n",rowString);
   }
   free(rowString);
}

The game being made is dots and boxes so width and height are the amount of boxes, the arrays are actually allocated as height*2+1 and width*2+1 and is set up to look like this if the height is 2 and width is4, note that the example has all the edges filled in already but normally the edges would just be white spaces:
x-x-x-x-x
| | | | |
x-x-x-x-x
| | | | |
x-x-x-x-x

When I print this the first time it looks like that, but if I try and print it again it looks like this:
x-x-x-x-x
| | | | |
x-x-x-x-x
| | | | |

Any idea on why this is happening?

A: Before the loop you allocate memory and assign it to the pointer variable rowString. But inside the loop you reassign the variable to point to somewhere else, loosing the original pointer to your allocated memory. Later when you try to free the memory you free the memory in the "2d matrix" instead of the memory you just allocated.
All of this leads to undefined behavior as you then later try to dereference the previously free'd memory (*(gameBoard + i)).
The obvious solution here is to not reassign the pointer, but to copy the string, e.g. with strcpy. Another pretty obvious solution would be to not allocate memory at all, and not even use the rowString variable, as you don't really need it but can use the pointer *(gameBoard + i) directly in your printf call.
