Reputation: 42
I am making a Rubik's Cube that can rotate it's rows and columns. My struct is this:
typedef struct
{
int **cell;
}face;
In this part I am allocating memory for cells. (X is user input)
face faceOne; //There are six of this faces
faceOne.cell = (int **)malloc(x * sizeof(int));
for(int i = 0; i < x; i++)
faceOne.cell[i] = (int *)malloc(x * sizeof(int));
Then I am filling these cells:
for (int i = 0; i < x; i++)
for (int j = 0; j < x; j++)
{
faceOne.cell[i][j] = 0;
printf("%d\n", i);
}
If x is bigger than 3, program crashes with Segmentation fault. How can i solve this?
Upvotes: 0
Views: 83
Reputation: 30936
faceOne.cell = (int **)malloc(x * sizeof(int));
would be
faceOne.cell = malloc(x * sizeof(int*));
Otherwise you are allocating memory for x
int variables and then storing int*
variable on it. In case sizeof(int) = sizeof(int*)
then it wont be any problem but on the system where this is not the case you have earned yoruself a undefined behavior.
To get rid of all this **
while using malloc
the best would be to do this
faceOne.cell = malloc(x * sizeof *faceOne.cell);
Similarly,
faceOne.cell[i] = malloc(x * sizeof *faceOne.cell[i] );
And also don't cast the return value of malloc
. This suppresses many warning generated by compiler and is unnecessary.
Apart from all this, have you ever wondered what would happen if malloc
did fail and returned NULL
? Then you are working on a NULL
and dereferencing it(Undefined behavior). Check the return value of malloc
, in case it returns NULL
handle the error and move on.
Upvotes: 2
Reputation: 28850
You want here
faceOne.cell = (int **)malloc(x * sizeof(int));
to allocate x
pointers to int, so this should be
faceOne.cell = malloc(x * sizeof(int *));
It seems on your system the size of a pointer (to int) is bigger than the size of an int ...
Also in C don't cast malloc() (see this)
Upvotes: 0