Bus error opening and mmap'ing a file

Viewed 9533

I want to create a file and map it into memory. I think that my code will work but when I run it I'm getting a "bus error". I searched google but I'm not sure how to fix the problem. Here is my code:

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/mman.h>
#include <string.h>

int main(void)
{
    int file_fd,page_size;
    char buffer[10]="perfect";
    char *map;

    file_fd=open("/tmp/test.txt",O_RDWR | O_CREAT | O_TRUNC ,(mode_t)0600);

    if(file_fd == -1)
    {
        perror("open");
        return 2;
    }

    page_size = getpagesize();

    map = mmap(0,page_size,PROT_READ | PROT_WRITE,MAP_SHARED,file_fd,page_size);

    if(map == MAP_FAILED)
    {
        perror("mmap");
        return 3;
    }

    strcpy(map, buffer);

    munmap(map, page_size);
    close(file_fd);
    return 0;
}
1 Answers
Related