1、使用 mallinfo 接口:
static void display_mallinfo(void)
{
struct mallinfo mi;
mi = mallinfo();
printf("Total non-mmapped bytes (arena): %d\n", mi.arena);
printf("# of free chunks (ordblks): %d\n", mi.ordblks);
printf("# of free fastbin blocks (smblks): %d\n", mi.smblks);
printf("# of mapped regions (hblks): %d\n", mi.hblks);
printf("Bytes in mapped regions (hblkhd): %d\n", mi.hblkhd);
printf("Max. total allocated space (usmblks): %d\n", mi.usmblks);
printf("Free bytes held in fastbins (fsmblks): %d\n", mi.fsmblks);
printf("Total allocated space (uordblks): %d\n", mi.uordblks);
printf("Total free space (fordblks): %d\n", mi.fordblks);
printf("Topmost releasable block (keepcost): %d\n", mi.keepcost);
}
2、使用sbrk(0) 调用得到当前进程的 heap 的 break point.
3、使用 strace -e trace=brk 跟踪进程的 brk 调用.
如
$strace -e trace=brk your_program
另外使用 -e trace=memory
Trace all memory mapping related system calls.
4、排除法
使用setrlimit 设置 RLIMIT_DATA 限制程序的heap 段大小,大致找到哪个值可以正常运行
RLIMIT_DATA
The maximum size of the process's data segment (initialized data, uninitialized data, and heap). This limit affects calls to brk(2) and sbrk(2), which fail with the error ENOMEM upon encountering the soft limit of this resource.
struct rlimit memory_limit;
memory_limit.rlim_cur = memory_limit.rlim_max = 1024 * 1024 * 70;
setrlimit(RLIMIT_DATA, &memory_limit);