On 16/02/2026 16:52, Ashutosh Bapat wrote:
2. to use madvise() the address needs to be backed by a file, so
memfd_create is a must.

It seems to work fine for anonymous mmapped memory here. See attached test program.

- Heikki
#include <sys/mman.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>

#define MEMORY_SIZE 4096 // Size of the memory segment in bytes

int main()
{
    void *memory_segment;
    
    memory_segment = mmap(NULL, MEMORY_SIZE, PROT_READ | PROT_WRITE,
			  MAP_ANONYMOUS | MAP_SHARED,
			  -1, 0);
    if (memory_segment == MAP_FAILED) {
        perror("mmap");
        exit(EXIT_FAILURE);
    }

    // Write data to the memory segment
    const char *test_string = "Hello, mmap!";
    size_t test_string_length = strlen(test_string) + 1;

    memcpy(memory_segment, test_string, test_string_length);
    
    // Read data back from the memory segment and print it
    printf("read before madvise(MADV_REMOVE) call: %s\n",
	   (char *) memory_segment);

    // Advise the system about the usage pattern of the memory segment
    printf("Calling madvise(MADV_REMOVE)\n");
    if (madvise(memory_segment, MEMORY_SIZE, MADV_REMOVE) == -1) {
        perror("madvise");
        exit(EXIT_FAILURE);
    }

    printf("read after madvise(MADV_REMOVE) call: %s\n",
	   (char *) memory_segment);

    // Write to it again
    memcpy(memory_segment, test_string, test_string_length);

    printf("read after writing it again: %s\n",
	   (char *) memory_segment);
    
    return 0;
}

Reply via email to