Re: madvise(MADV_FREE) doesn't work in some cases?

From: Vitaliy Gusev <gusev.vitaliy_at_gmail.com>
Date: Mon, 05 Jul 2021 19:31:26 UTC
Further investigation shown that if use MADV_DONTNEED in simple mmap test program and run it twice (second after the first finishes madvise()), then memory is not freed at all and first instance is killed.

If change MADV_DONTNEED flag with  MADV_FREE, then memory is freed.


Code is:

#include <sys/mman.h>
#include <err.h>
#include <stdint.h>
#include <sys/cdefs.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
	size_t len = (size_t)(argc > 1 ? atoi(argv[1]) : 1024) * 1024 * 1024;
	uint8_t *ptr, *end;
	uint8_t *p;
	int pagesz = (1<<12);

	ptr = (uint8_t *)mmap(NULL, len, PROT_WRITE | PROT_READ, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
	if (ptr == MAP_FAILED)
		err(1, "cannot mmap");

	end = ptr + len;

	p = ptr;
	while (p < end) {
		*(uint64_t *)p = 1;
		p += pagesz;
	}

	sleep(1);
	printf("madvise\n");

	p = ptr;
	while (p < end) {
		int error;

		error = madvise(p, pagesz, MADV_DONTNEED);
		if (error) {
			err(1, "cannot madvise");
		}
		p += pagesz;
	}

	printf("press Enter to exit\n");
	getchar();
}