A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

  • Index
  • » C
  • » loading flat in memory using mmap

#1 2009-11-02 03:25 AM

Registered: 2009-10-30
Posts: 5

Re: loading flat in memory using mmap

  I am using mmap to map the content of file however all lines of the files are mapped ,  length  parameter of mmap does not work.

let file1 has entry like

hello World
Welcome to the World.

file_memory= mmap(NULL,10,PROT_READ, MAP_PRIVATE, fd, 0);

I am assuming, it will return 10 char starting from 0  however printing of file_memory   display whole content of file(hello World
Welcome to the World.)

can some tell me why above call does not print  only hello World


#2 2009-11-02 03:26 PM

From: Boston, MA
Registered: 2002-06-12
Posts: 3,839

Re: loading flat in memory using mmap

Read the man page: "A  file is mapped in multiples of the page size."...  You can't
map a partial page of data...  Ie: your passed length will always get rounded up to
the next highest page boundry...  Which is likely 4K...  So, you can only limit the
granularity of the mapping to separate chunks of that size...

But, note: even if it worked like you wanted, and only mapped in 10 bytes, your
simple printing of the returned pointer as a string (presumably with printf("%s") or
fputs() or something) would result in you seg-faulting, as you read off the end of
the mapped memory into unmapped memory...  Because, there would still be no
null-termination of the string, unless you happened to store null chars in the file
itself...  mmap() certainly isn't going to null-terminate your strings for you...  (Though,
it will null-pad out the empty space in the final non-full page of memory, if the file
doesn't completely fill the page...  Which is why you end up with a defacto null
termination of your short file contents there...)


  • Index
  • » C
  • » loading flat in memory using mmap

Board footer

Powered by FluxBB