I have a weird problem and I’m not sure how to approach it.
I’m reading a 50×50 chars textfile and want to write it into a 50×51 dynamic array (filling the 51th slot with ‘\0’).
Afterwards I’m printing the entire array onto the console.
It should show 50 lines with 50 chars each, as this was the input.
It works quite well too – with the exception of the first line. For some reason is always wrong.
#define FIELD_SIZE 50
int main(int argc, char** args){
char* data = ReadFile("start.txt");
char** map = (char**) malloc( FIELD_SIZE );
if(map==NULL)
__debugbreak();
{
int i;
for(i = 0; i < FIELD_SIZE; i+=1){
map[i] = (char*) malloc(FIELD_SIZE+1);
if(map[i]==NULL)
__debugbreak();
//(FIELD_SIZE+1) in order to skip the '\n' at the end of each line.
memcpy( &map[i][0], &data[i*(FIELD_SIZE+1)], FIELD_SIZE);
map[i][FIELD_SIZE] = '\0';
}
}
{
int i;
for(i = 0; i < FIELD_SIZE; i+=1){
printf("%s\n", map[i]); //<-- prints something bad for i==0
}
}
free(data);
return 0;
}
Here’s how my console looks like after program execution:

The first line is supposed to be “aaaaaaaaaaaaa…” too.
So it seems like a bad pointer or something.
If I’m reducing FIELD_SIZE to 20 instead (and reading in a 20×20 text file respectively) it works fine, however.
I don’t see a connection between the array size and the first index not working though. Since malloc never returned 0 there’s no problem with allocation.
I’m using VS2010 C++ to compile the program, but I have to limit myself to the C subset.
char** map = (char**) malloc( FIELD_SIZE );
char** map = (char**) malloc( FIELD_SIZE * sizeof(char*));
I don’t know if this would be the bug in your code.
You allocate 50 bytes, but need 50 bytes x 4 bytes/pointer in map.