Karthik R Karthik R - 3 years ago 160
C Question

Segmentation fault while using malloc and taking input

I have something of this sort:

int n,m;
scanf("%d %d",&m,&n);
int *arr = malloc(sizeof(int)*n*m);
for(int i=0;i<m*n;scanf("%d",arr+i),i++);


Now for say n=2 and m = 3, It accepts the first five numbers, and gives a segmentation fault on the sixth number. I tried printing stuff immediately after the loop, but its not being printed, any idea what the problem could be? I've used similar constructs extensively and have never encountered a problem before.

EDIT 1:
The problem was later on in the program, but the thing is I had a printf immediately after the loop, and it didn't print anything, so I assumed that it had to be here. Why didn't the printf print anything? Does it have something to do with parallel execution? And sorry for the bad format, I'm new to stack overflow.

Answer Source

Try this,

int n,m;
printf( "Enter two digits" );
int scanCount = scanf( "%d %d", &m, &n );
if( scanCount < 2 ){   
    perror("Input");
    exit(EXIT_FAILURE);   
}
scanCount = 0;
size_t size = sizeof( int ) * n * m;
int * arr = (int *) malloc( size );
if ( arr == NULL ) { 
    perror("malloc");
    exit(EXIT_FAILURE);
};
for( int i = 0; i < m * n; i++ ){
    if ( scanf( "%d", arr + i ) )
        scanCount++;
}
if( scanCount < m*n ){   
    perror("Input");
    exit(EXIT_FAILURE);
}
for( int i=0; i<n*m; i++ ){
    printf( "\nValue at %d : %d\n", i, *( arr + i ) );
}

I have modified the above given program a little bit, and now it works for me. The malloc function expects "std::size_t size" ( we can also provide integer values ) as argument which is the size of the memory we need to allocate. Please visit http://en.cppreference.com/w/cpp/memory/c/malloc for any reference.

Also we should specify the type of the memory we are creating ( otherwise it may produce an error in some compilers, like this "invalid conversion from 'void*' to 'int*'" ). In this case we are creting an array of integers and we can use type cating, for example (int *) malloc( size).

It is better to implement some error handlers for failed memory allocation and inputs through scanf ( check the return values of malloc and scanf )

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download