动态分配数组的末尾

这是我的第一个问题。对不起,如果我做错了。感谢您的理解。

我有一个动态分配的数组,

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 + 10)个索引处的内容。打印“ 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".

为什么[i + 10]没有给出段错误?

感谢您的时间。

评论
  • jdolor
    jdolor 回复

    这是一个数组越界逻辑错误,但是很有可能它不会引发分段错误,因为malloc分配的内存比您预期的要多。

    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.

    对于系统来说,为您提供比您要求的对齐方式和其他复杂的操作系统原因(程序员真正不需要了解或理解的原因)多得多的内存并不罕见。

    尝试在您的系统上编译并运行该程序,以查看我在说什么的证据:

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