Search code examples
cunixmmap

MMAP segmentation fault


int  fp, page;
char *data;

if(argc > 1){
    printf("Read the docs");
    exit(1);
}

fp = open("log.txt", O_RDONLY); //Opening file to read 
page = getpagesize();
data = mmap(0, page, PROT_READ, 0,fp, 0);

initscr(); // Creating the ncurse screen
clear();
move(0, 0); 
printw("%s", data);
endwin(); //Ends window
fclose(fp); //Closing file 
return 0;

Here is my code I keep getting a segmentation fault for some reason. All my header files have been included so that's not the problem (clearly, because its something to do with memory). Thanks in advance.

Edit: Got it - it wasn't being formatted as a string. and also had to use stat() to get the file info rather than getpagesize()


Solution

  • The second argument to mmap should not be page size, it should be the size of your file. Here is a nice example.