Keeto
Keeto

Reputation: 4198

Memory reallocation using mremap

I am trying to allocate two different 4096 bytes using malloc and initialize these allocations with different values. Afterwards, I want one of the pointers to point to the other allocation "without" changing the value of p1 and "without" copying the data. I want to "remap" the second allocation to the first allocation which should basically change the virtual address in the page table of the process, i.e. no copying is involved. When I run this code, I get that mremap failed. Any idea how to accomplish this?

int main(){
    char *p1 = (char *)malloc(4096);
    memset(p1, 'a', 4096);
    char *p2 = (char *)malloc(4096);
    memset(p2, 'b', 4096);
    printf("p1 is %c at address %p\n", p1[0], p1);
    printf("p2 is %c at address &p\n", p2[0], p2);
    free(p1);
    /* remapping virtual addresses */
    void *p0 = mremap(p2, 4096, 4096, MREMAP_MAYMOVE | MREMAP_FIXED, p1);
    /* checking */
    printf("p0 is %c at address %p\n", p0[c], p0);
    return 0;
}

expected output: p1 is a at address xxx p2 is b at address yyy p0 is b at address xxx

Upvotes: 1

Views: 3231

Answers (1)

Crowman
Crowman

Reputation: 25926

The addresses returned by malloc() are probably not page-aligned, so mremap() is setting errno to EINVAL. If I use mmap() instead of malloc(), and fix the syntax errors in your code:

#define _GNU_SOURCE 1

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>

int main(void) {
    char *p1 = mmap(NULL, 4096, PROT_READ | PROT_WRITE,
                    MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
    memset(p1, 'a', 4096);

    char *p2 = mmap(NULL, 4096, PROT_READ | PROT_WRITE,
                    MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
    memset(p2, 'b', 4096);

    printf("p1 is %c at address %p\n", p1[0], (void *)p1);
    printf("p2 is %c at address %p\n", p2[0], (void *)p2);

    void *p0 = mremap(p2, 4096, 4096, MREMAP_MAYMOVE | MREMAP_FIXED, p1);
    if ( p0 == MAP_FAILED ) {
        perror("mremap: mremap failed");
        return EXIT_FAILURE;
    }

    printf("p0 is %c at address %p\n", ((char *)p0)[0], p0);
    return EXIT_SUCCESS;
}

then I get:

paul@local:~/src/c/scratch$ ./mremap
p1 is a at address 0x7f5addb71000
p2 is b at address 0x7f5addb70000
p0 is b at address 0x7f5addb71000
paul@local:~/src/c/scratch$ 

Upvotes: 5

Related Questions