Why do I get a segfault when writing to a file using mmap?

517 Views Asked by At

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.

0

There are 0 best solutions below