Search code examples
cdynamicallocationansi-c

Dynamic allocation failing to scan number


#include <stdio.h>
#include <stdlib.h>

main(){
    int *ptr,r,c,i,j,min;
    printf("Give me the size of rows and columns\n");
    scanf("%d%d",&r,&c);
    int mini[r];
    ptr=(int*)malloc(r*c*sizeof(int));
    if(ptr== NULL){
        printf("Memory not allocated");
    }
    else{

        for(i=0;i<r;i++){
            for(j=0;j<c;j++){
            printf("Give me the value ");

            scanf("%d",&ptr+(i*c+j));
            }
        }

        for(i=0;i<r;i++){
            min=*(ptr+i*c); 
            for(j=0;j<c;j++){
                if (*(ptr+i*c)<min){
                    min = *(ptr+i*c);
                }
                mini[i]=min;
            }
        }
        for(i=0;i<r;i++){
            printf("%d",mini[i]);

        }
        free(ptr);

    }
}

It gets the row and column (r and c ) values without a problem but it crashes as soon as i get to the point of scaning the allocated memory elements. For example if i set r==3 and c==4 then it gets to asking the 10th element of the 12 and then it crashes saying that filename.exe has stopped working.

From my experience I think this has something to do with the scanf() function. I also tried without the & in the scanf, scanf("%d",ptr +(i*c +j)) but then it crashes as soon as it gets to read the first element.

In another much simpler program I wrote to check it the latter scenario of scanf() does not present any problems and the program runs as it was supposed to.


Solution

  • This is wrong

    scanf("%d",&ptr+(i*c+j));
    

    it should be

    scanf("%d", &(*(ptr + i*c + j)));
    

    or since, the ptr points to the addres, you should not dereference the pointer and then pass the address, just

    scanf("%d", ptr + i*c + j);
    

    in your code you are passing the address of the pointer ptr incremented by i * c + j, which is presumably an invalid address, and hence the segmentation fault occur.

    Also, it's not the first time I see a scanf() where the return value is ignored, if you type a string then a crash will occur.

    You should ensure that an integer was read with

    if (scanf("%d", &(*(ptr + i * c + j))) == 1)
    

    if the condition is false, then no value was read, for example if you type text instead of numbers.