Reputation: 12064
Why does this code segment give segmentation fault?
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <string.h>
int main()
{
void *ptr;
ptr=mmap(NULL, 10, PROT_READ|PROT_WRITE, MAP_ANONYMOUS, -1, 0);
strcpy(ptr, "Hello");
}
Or better, i would like to have: char *ptr=malloc(10);
then pass this argument to mmap. Both gives SIGSEGV.
Upvotes: 1
Views: 2498
Reputation: 1
You probably get MAP_FAILED
(that is, (void*)-1
) as the result of your mmap
with EINVAL
in errno
. The man page of mmap(2)
says that it fails with
EINVAL We don't like addr, length, or offset (e.g., they are too large,
or not aligned on a page boundary).
Your second argument to mmap
(called length
in the man page) cannot be 10. It should be a multiple of the page length (at least 4K).
Upvotes: 0
Reputation: 206679
Check the return values of your system calls!
The flags
argument to mmap
must have exactly one of these two options:
MAP_SHARED
Share this mapping. Updates to the mapping are visible to other processes
that map this file, and are carried through to the underlying file. The file
may not actually be updated until msync(2) or munmap() is called.
MAP_PRIVATE
Create a private copy-on-write mapping. Updates to the mapping are not
visible to other processes mapping the same file, and are not carried through
to the underlying file. It is unspecified whether changes made to the file
after the mmap() call are visible in the mapped region.
You're not providing that, so mmap
is most likely failing (returning (void*)-1
) with errno
set to EINVAL
.
Upvotes: 10