Hello. I'm having trouble with a structure that points to a dynamically allocated 2D array. For some reason, after I allocate the array, it becomes "deallocated" in the middle of the program.
I have a pointer to a structure which has a pointer to a 2D array. The full program gives a bus error, which happens when I try to access a cell in the structure's array. I've removed a bunch of the code that actually does stuff for this post. I can still see though where the problem is coming from through the debugger (I just have no clue why it's there!)
The main program:
Code:
int main()
{
Map *map_p = map_create_p(10, 10);
Creature *player_p = creature_create_p();
printf("This is just busywork.\n");
return 0;
}
This is the problem structure:
Code:
struct map
{
unsigned int maxRows;
unsigned int maxCols;
char **tiles_p; // A 2D array
};
typedef struct map Map;
How I create a Map structure:
Code:
Map *map_create_p(unsigned int maxRows, unsigned int maxCols)
{
int r, c;
Map *map_p;
map_p = malloc(sizeof(map_p));
map_p->maxRows = maxRows;
map_p->maxCols = maxCols;
map_p->tiles_p = calloc(maxRows, sizeof(map_p->tiles_p));
for (r = 0; r < maxRows; r++)
{
map_p->tiles_p[r] = calloc(maxCols, sizeof(map_p->tiles[r]));
for (c = 0; c < maxCols; c++)
{
map_p->tiles_p[r][c] = '.';
}
}
return map_p;
}
When I first create a Map structure, I can access the elements of its tiles_p array fine. But after a few lines I can't access them anymore.
This is what running it through gdb is like (with spaces added for emphasis):
Code:
(gdb) br 13
Breakpoint 1 at 0x109e4: file main.c, line 13.
(gdb) r
Starting program: /users/cs/macdona2/other/tehrogue/tehrogue
Breakpoint 1, main () at main.c:13
13 Map *map_p = map_create_p(10, 10);
(gdb) print map_p
$1 = (Map *) 0x0
(gdb) n
15 Creature *player_p = creature_create_p();
(gdb) print map_p
$2 = (Map *) 0x210e0
(gdb) print map_p->tiles_p[0][0]
$3 = 46 '.' // *** Everything is fine. ***
(gdb) print player_p
$4 = (Creature *) 0x0
(gdb) n
23 printf("This is just busywork.\n");
(gdb) print map_p->tiles_p[0][0]
Cannot access memory at address 0x2151000 // *** How did this happen?! ***
(gdb)
The strange thing is that this only happens when I create the Creature structure. If I comment that line out the array in the Map structure stays fine.
Here's the Creature structure by the way:
Code:
struct creature
{
unsigned int row;
unsigned int col;
Map *map_p;
char symbol;
};
typedef struct creature Creature;
And here is how I create a Creature structure:
Code:
Creature *creature_create_p()
{
Creature *cp = malloc(sizeof(cp));
cp->row = 0;
cp-col = 0;
cp->map_p = NULL;
return cp;
}
If someone can help me figure this out I'd really appreciate it.
Thanks.