I am allocating this 2d array and well, let me post the code first:
Code:
struct cell {
int oldPos, newPos;
};
int main(void) {
int x, y;
struct cell **world;
world = malloc(LINES * sizeof (struct cell*));
for(x = 0;x < COLS; x++) {
world[x] = malloc(COLS * sizeof (struct cell));
}
for(x = 0; x < COLS; x++) {
for(y = 0; y < LINES; y++) {
world[x][y].newPos = 0;
}
}
return 0;
}
I know that I am not checking return values or all of that good stuff, and LINES and COLS are defined in a header as say 80 and 24 respectively. When I run the program, it segfaults when x reaches 27 in the assignment loop, but using a debugger, I found world[28][0] was valid. It appears that every other element past 27 is valid? Here is the gdb output from some commands.
Originally Posted by
gdb
(gdb) print world[27][0]
Cannot access memory at address 0x0
(gdb) print world[28][0]
$3 = {oldPos = 0, newPos = 0}
(gdb) print world[29][0]
Cannot access memory at address 0x0
(gdb) print world[30][0]
$4 = {oldPos = 0, newPos = 0}
(gdb) print world[31][0]
Cannot access memory at address 0x0
(gdb) print world[32][0]
$5 = {oldPos = 0, newPos = 0}
(gdb) print world[33][0]
Cannot access memory at address 0x0
(gdb) print world[34][0]
$6 = {oldPos = 0, newPos = 0}
(gdb) print world[35][0]
Cannot access memory at address 0x0