Link to home
Start Free TrialLog in
Avatar of zizi21
zizi21

asked on

mmap gives segmentation fault - pls help

hi,

i tried  a big file and the program gave segmentation fault but when i  tried with a smaller file, mmap works fine. i thought that with mmap, the system only loads the required page. so, it is not necessary to have enough memory on the server.

but now, it looks like when i give the length of the file to mmap, it maps that number of bytes. is this true ?

so, if the system doesn't have enough memory, there would be seg fault ??

thanks a million
ASKER CERTIFIED SOLUTION
Avatar of cconstable_work
cconstable_work

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of zizi21
zizi21

ASKER

thanks for the link but it is confusing. some of the expert advised that the whole file will be loaded and some advised that it will not be loaded.
A seg fault is not caused by the system not having enough memory.
A seg fault would be from something like trying to write to a location in memory that is not allowed (read only) or not initialized.
perhaps you are unmapping too early?

Can you show the code where you are setting the length?
Avatar of zizi21

ASKER

i used gdb and i am getting seg fault at memcpy. the code is long, so i am putting parts of it
while(1)
{
      memcpy(&x,&a[x],sizeof(unsigned int));
}

size = s.st_size;
        a = (unsigned int*) mmap(NULL, size, PROT_WRITE|PROT_READ, MAP_SHARED, fp, 0);

how is the while loop terminating..

i assume.. you map the file first and used it in the loop.

If the address where file is mapped is 'a' and the size mapped is size, then only memory from a to (a+size - 1)  is valid. If you cross that , you will get seg fault. Ofcourse, the end of the mapped segment might be rounded up to a page boundary, but from the programs logic, it shouldnt cross a+size -1 while reading from the mmapped region...

so put a terminating condition on the loop.
Ah I see you are trying to write to 0, this will cause a seq fault on certain operating systems that implement mmap_min_addr protection using LSM http://en.wikipedia.org/wiki/Linux_Security_Modules.
while(1)
{
      memcpy(&x,&a[x],sizeof(unsigned int));
}


also &a[x] dont look correct to me here.... if x is very large.. you will very easily get seg fault
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of zizi21

ASKER

trying it  now..thakns a millon
Also put a check for the return value for mmap... make sure its not failing before proceeding further..