0

I recently learned from a YouTube video that we can read from or write to files by mapping them into memory. The video showed how read some contents from a text file and print them out and also change some of characters of the text file. I tried to write some contents to a file using this technique but whenever I build and run my code, I face segmentation fault (core dumped) error and I don't know why.

#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("information.dat", "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);
}

My operating system is ubuntu 18.04 and I use GCC 7.3.0 compiler.

4
  • 2
    mmap() cannot be used to increase the size of the file. Commented Jan 27, 2021 at 17:24
  • 1
    You need to call ftruncate() to set the size of the file before mapping it. Commented Jan 27, 2021 at 17:26
  • 1
    You should check the return value of mmap. It may return MAP_FAILED to indicate an error. In this case, memory dereferenced. Use a debugger to see at which point in your program you get the segmentation fault. Commented Jan 27, 2021 at 17:30
  • MAP_PRIVATE will mean all writes to the file never get saved to disk: "If MAP_PRIVATE is specified, modifications to the mapped data by the calling process shall be visible only to the calling process and shall not change the underlying object." Commented Jan 27, 2021 at 17:39

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.