Reputation: 17
Can anyone explain what is the wrong of the code below? İf I give the "line" variable as 1,2,3 or 4, it runs correctly. But after 4 it just shows a count of row correctly, the count of columns is not correct.
output of dev-c/c++ on windows >> "return value 3221225477"
output of gcc on mac >> "Segmentation fault: 11"
#include<stdio.h>
#include<stdlib.h>
int main(){
int **matris;
int size;
int i, j;
printf( "Size >> " );
scanf( "%d", &size );
matris = (int **)malloc( size * sizeof(int) );
if( matris == NULL )
printf( "It's required more memory'!" );
for( i = 0; i < size; i++ ) {
matris[i] = malloc( size * sizeof(int) );
if( matris[i] == NULL )
printf( "It's required more memory'!!" );
}
for( i = 0; i < size; i++ ) {
for( j = 0; j < size; j++ ){
matris[i][j]=i+1;
printf( "%d ", matris[i][j] );
}
printf( "\n" );
}
for( i = 0; i < size; i++ ) {
free( matris[i] );
}
free( matris );
return 0;
}
Upvotes: 0
Views: 167
Reputation: 3272
The line matris = (int **)malloc( size * sizeof(int) );
is incorrect as you want to create an array of int pointers and not of int. Changing the int
to int*
works.
Upvotes: 0
Reputation: 15032
matris = (int **)malloc( size * sizeof(int) );
with especially ( size * sizeof(int) )
is wrong. You need to allocate memory for objects of type int*
(pointer to int
), not int
.
This is a problem if sizeof(int) < sizeof(int*)
on your implementation -> Translated: The size of an object of type pointer to int
is bigger than the size of an object of type int
, which is quite common.
Then you get a segmentation fault, because you access memory beyond the bounds of the pointer array matris
in the following code.
Use:
matris = malloc ( sizeof(int*) * size );
or even better
matris = malloc ( sizeof(*matris) * size );
Side Notes:
You don't need to cast the return of malloc()
. The returned pointer is automatically aligned. Do I cast the result of malloc?
sizeof(*matris)
requires less maintenance and is more safe if the type of matris
and the pointed objects changes.
Set the sizeof
operation first to ensure size_t
arithmetic, since size
is of type int
.
Upvotes: 1