Quick actions

cmd+k|ctrl+k

Navigation

Languages

Virtual memory mapping

Snippet info

Language

C

Visibility

public

Author

evine

Created

2021-01-12T20:01:38Z

Updated

2021-01-15T15:39:50Z

#define _GNU_SOURCE
#include <sys/mman.h>
#include <unistd.h>
#include <stdio.h>

int main() {
    size_t size = 4096 * 2;
    
    int fd = memfd_create("example", 0);
    if (fd == -1)
        return 0;
        
    ftruncate(fd, size);
    
    char *orig = (char *)mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    char *copy = (char *)mmap(0, size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
    
    orig[0] += 100;
    copy[0] += 10;
    orig[0] += 1;
    
    orig[4095] = 1;
    orig[4096] = 1;
    
    printf("%p, %p, diff: %zi\n", orig, copy, orig - copy);
    printf("index  orig  copy\n");
    printf("[0]    %i   %i\n", orig[0], copy[0]);
    printf("[4095] %i     %i\n", orig[4095], copy[4095]);
    printf("[4096] %i     %i\n", orig[4096], copy[4096]);
    
    munmap(copy, size);
    munmap(orig, size);
    
    return 0;
}
INFO