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.
Check the return values of your system calls!
The
flagsargument tommapmust have exactly one of these two options:You’re not providing that, so
mmapis most likely failing (returning(void*)-1) witherrnoset toEINVAL.