为什么在使用 mmap 写入文件时会出现段错误?

问题描述

我最近从 YouTube 视频中了解到,我们可以通过将文件映射到内存来读取或写入文件。该视频展示了如何从文本文件中读取一些内容并将其打印出来,以及如何更改文本文件的一些字符。我尝试使用这种技术将一些内容写入文件,但是每当我构建和运行我的代码时,我都会遇到分段错误(核心转储)错误,我不知道为什么。

#include<stdio.h>
#include<stdlib.h>
#include<sys/mman.h>
#define SIZE 5 * sizeof(float)

int main()
{
    float *info = (float*) malloc (SIZE);
    if(info == NULL)
    {
        printf("Unable to allocate memory.");
        exit(EXIT_FAILURE);
    }

    for(int counter = 0; counter < 5; counter++)
        *(info + counter) = counter + 1;

    FILE *file = fopen("@R_786_404[email protected]","w");
    if(file == NULL)
    {
        printf("Unable to open the file.");
        exit(EXIT_FAILURE);
    }

    float *memory = mmap(NULL,SIZE,PROT_WRITE,MAP_PRIVATE,fileno(file),0);

    for(int counter = 0; counter < 5; counter++)
    {
        *(memory + counter) = *(info + counter);
        printf("%5.2f has been saved in the file.\n",*(info + counter));
    }

    fclose(file);
    free(info);
}

我的操作系统是 ubuntu 18.04,我使用 GCC 7.3.0 编译器。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)