brk/sbrk和mmap行为分析程序

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

// #include <malloc.h>
// int mallopt(int param, int value);

// info mallopt, 一些系统可以man mallopt
// M_TRIM_THRESHOLD: 紧缩内存阈值,对应的环境变量为MALLOC_TRIM_THRESHOLD_
// M_MMAP_THRESHOLD: 使用mmap而非brk/sbrk分配内存阈值,即超过该值的malloc分配将使用mmap
// ,否则使用brk/sbrk分配内存,对应的环境变量为MALLOC_MMAP_THRESHOLD_
// 请注意:如今的glibc使用了动态的阈值,初始值为128*1024,
// 下限为0,上限由DEFAULT_MMAP_THRESHOLD_MAX决定,32位系统为512*1024,64位系统为4*1024*1024*sizeof(long)
// mmap分配内存必须是页对齐的:
// Allocating memory using mmap(2) has the significant advantage that the allocated memory blocks can always be independently
// released back to the system.  (By contrast, the heap can be trimmed only if memory is freed at the top end.) 
// 相关函数:
// mtrace muntrace mcheck mcheck_pedantic mcheck_check_all mprobe
// malloc_stats mallinfo malloc_trim malloc_info

// mmap分配的内存在调用munmap后会立即返回给系统,而brk/sbrk而受M_TRIM_THRESHOLD的影响
// 但brk/sbrk分配的内存是否立即归还给系统,不仅受M_TRIM_THRESHOLD的影响,还要看高地址端(栓)的内存是否已经释放:
// 假如依次malloc了str1、str2、str3,即使它们都是brk/sbrk分配的,如果没有释放str3,只释放了str1和str2,
// 就算两者加起来超过了M_TRIM_THRESHOLD,因为str3的存在,str1和str2也不能立即归还可以系统,但可以被重用
// 更多信息,请参考man手册:http://man7.org/linux/man-pages/man3/mallopt.3.html

// argv[1] 每次分配的字节数,如果没有指定,则使用32
// 请观察不同值时malloc和free的行为
// 当argv[1]为131072,即为128K时,使用的是mmap分配,每一步的malloc和free都可以从top中观察到反应
// gcc -g -o x x.c
int main(int argc, char* argv[])
{
	char* str[3];
	int BYTES = (argc > 0)? atoi(argv[1]): 32;
	// 128 * 1024 = 131072

	printf("
Please type "top -p %d" to watch VIRT, press ENTER to continue", getpid());
	getchar();

	str[0] = (char*)malloc(BYTES);
	printf("%dBYTES allocated, press ENTER to continue", BYTES);
	getchar();
	
	str[1] = (char*)malloc(BYTES);
	printf("%dBYTES allocated, press ENTER to continue", BYTES);
	getchar();

	str[2] = (char*)malloc(BYTES);
	printf("%dBYTES allocated, press ENTER to continue", BYTES);
	getchar();

	printf("FREE phase, press ENTER to continue");
	getchar();

	free(str[0]);
	printf("%dBYTES freed, press ENTER to continue", BYTES);
	getchar();

	free(str[1]);
	printf("%dBYTES freed, press ENTER to continue", BYTES);
	getchar();

	free(str[2]);
	printf("%dBYTES freed, press ENTER to continue", BYTES);
	getchar();

	printf("Press ENTER to exit
");
	getchar();

	return 0;
}

原文地址:https://www.cnblogs.com/aquester/p/9891636.html