Reputation: 4185
I should be allocating enough memory for my char**. I used gdb and found the point of the segmentation fault. I've been stuck on this part for about an hour and can't seem to figure out why I'm segfaulting.
Output of program:
size: 10, 20
start: 1, 1
end: 10, 20
Segmentation fault (core dumped)
10 = m1.xsize
20 = m1.ysize
1 = m1.xstart
1 = m1.ystart
10 = m1.xend
20 = m1.yend
snippet of my code:
typedef struct mazeStruct
{
char** arr;
int xsize, ysize;
int xstart, ystart;
int xend, yend;
} maze;
/* read in the size, starting and ending positions in the maze */
fscanf (src, "%d %d", &m1.xsize, &m1.ysize);
fscanf (src, "%d %d", &m1.xstart, &m1.ystart);
fscanf (src, "%d %d", &m1.xend, &m1.yend);
/* print them out to verify the input */
printf ("size: %d, %d\n", m1.xsize, m1.ysize);
printf ("start: %d, %d\n", m1.xstart, m1.ystart);
printf ("end: %d, %d\n\n", m1.xend, m1.yend);
//allocating memory for 2d char array
m1.arr = (char**)malloc(m1.xsize+2 * sizeof(char*));
for(i = 0; i < m1.xsize+2; i++)
m1.arr[i] = (char*)malloc(m1.ysize+2);
/* initialize the maze to empty */
for (i = 0; i < m1.xsize+2; i++) <---- when i = 6 it seg faults
for (j = 0; j < m1.ysize+2; j++)
m1.arr[i][j] = '.';
Am I not allocating enough memory or what am I doing wrong?
Upvotes: 0
Views: 98
Reputation: 881543
Your expression:
m1.xsize + 2 * sizeof(char*)
is equivalent to:
(m1.xsize) + (2 * sizeof(char*))
due to precedence of operators, which is not what you want. You need to instead use:
(m1.xsize + 2) * sizeof(char*)
By way of example, let's say you have m1.xsize
set to 20 and your pointer size is four bytes. Hence you need space for 22 pointers, which is 88 bytes. The expression m1.xsize + 2 * sizeof(char*)
gives you 20 plus double the size of a pointer, totaling 28 bytes, nowhere near enough for what you want to do.
As an aside, you should also stop casting the return value of malloc()
since it can hide certain subtle errors. C is perfectly capable of implicitly casting the void*
returned from malloc()
into any other pointer type.
Upvotes: 5