Search code examples
cdynamic-arrays

End of dynamically allocated array


that's my first question. Sorry if I do something wrong. Thanks for your understanding.

I have a dynamically allocated array,

int *read_array(char *file_path , int *arr){

    int max = 0 ,min = 0, i = 0;
    FILE *fp = fopen(file_path,"r");

    arr= malloc(1 * sizeof(int));

    fscanf(fp, "%d,", &arr[i] );
    max = arr[i];
    min = arr[i];
    i++;
    arr = realloc(arr , i * sizeof(int));

    while(fscanf(fp, "%d,", &arr[i] ) != EOF){

        if(max < arr[i]){
            max = arr[i];
        }
        else if(min > arr[i] ){
            min = arr[i];
        }

        i++;
        arr = realloc(arr , (i +1) * sizeof(int));

    }
    printf("%d\n",arr[i + 10]);
    free(arr);
}

I tried to print what is at (i+10)th index of my array. It prints "0".

But when I made that printf like printf("%d\n",arr[i + 100000]); I got a seg fault as I expected. But I think I allocated as much memory as "i".

Why arr[i+10] is not giving seg fault ?

Thank you for your time.


Solution

  • This is an array-out-of-bounds logic error, but there's a good chance it's not throwing a segmentation fault because malloc allocated more memory than you were expecting.

    The C standard does not require malloc() to return a pointer to exactly the amount of memory you asked for. The parameter you pass to malloc() is treated by the system as the minimum required size for the chunk of memory it returns to you.

    It is not uncommon for the system to give you quite a bit more memory than you ask for for alignment and other complicated-operating-system reasons that coders really don't need to know about or understand.

    Try compiling and running this program on your system to see proof of what I'm talking about:

    #include <stdio.h>
    #include <stdlib.h>
    #include <malloc.h>
    
    #define VALUE 150 //Or whatever you want
    
    int main(){
      for(int i=0;i<VALUE;++i){
        void *pt=malloc((size_t)i);
        printf("Asked for %d bytes, received %zd bytes\n",i,malloc_usable_size(pt));
        free(pt);
      }
    }