c - 为什么我无法访问所定位的内存?

标签 c memory memory-management

程序将数据从文件读取到数组,load_data将数据加载到数组 ar 。但是为什么我会得到 Segmentation fault (core dumped)当我访问 main 中的该数组时.

#include <stdio.h>
#include <stdlib.h> 
long int load_data(double * ar);

int main(void)
{
    long int n,i;
    double * ar; 
    FILE * fp; 
    double number;

    n=load_data(ar);

    fp = fopen("data-copy.txt","w");
    //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    for(i=0; i<n; i++)
        fprintf(fp,"%lf\n", ar[i]); //problem here! I can't access!
    //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    fclose(fp);

    printf("The number of elements in the file is:%ld\n",n);
}

long int load_data(double * ar) 
{
   FILE * fp; 
   double temp;
   long int n=0,i;

   fp = fopen("data.txt","r");
   while(fscanf(fp,"%lf",&temp)==1)
       n++;
   fclose(fp);
   //load memory
   ar = (double*)malloc(sizeof(double)*n);

   fp = fopen("data.txt","r");
   for(i=0; i<n; i++)
   {
       fscanf(fp,"%lf",ar+i);
   //    printf("%lf\n",ar[i]);//This print well!
   }
   fclose(fp);

   return n;
}

最佳答案

C 中的所有函数参数都是按值传递。

你的main函数复制ar的值(垃圾值)到编译器放置函数参数的地方(通常在指定的寄存器或在堆栈上)。

在函数 load_data 中,ar 的副本更改为指向内存块的指针,但原始 ar 位于main 没有改变并且仍然是垃圾。

当您退出该函数时,您将丢弃 ar 的副本(泄漏 malloc block )。然后你尝试取消引用原始的ar,它仍然是垃圾。

关于c - 为什么我无法访问所定位的内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32482419/

相关文章:

c - 为什么此代码在 msdev 上运行时会出现访问冲突?

python - 使用 Python 多处理的高内存使用率

删除后无法写入闪存

Android - 获取分配的内存

c - Micriμm μC/OS-III RTOS 中的分配和释放

c - 当所有变量都被使用时,不会被堆叠、分配或(最近)释放

c - 在 C 中的 IP header 中分配 IP 地址

c - 用户输入另一个数据时的数组放置

c - 内存地址如何放置在二进制文件中?

c++ - 未解析的外部符号 _D3D10CreateDeviceAndSwapChain@32 在函数“public : bool 中引用