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.
", *(info + counter));
}
fclose(file);
free(info);
}
My operating system is ubuntu 18.04 and I use GCC 7.3.0 compiler.
question from:
https://stackoverflow.com/questions/65924172/why-do-i-get-a-segfault-when-writing-to-a-file-using-mmap 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…