#include
void * malloc (size_t size);
void * calloc (size_t num, size_t size);
void * realloc(void * ptr, size_t size);
void free (void * ptr);
在写这篇文章时,笔者犯了一个错误,就是讨论的是 linux, 却在 windows 平台上做实验,cygwin 虽然是 linux 的模拟器,但最终调用的还是 windows API. 在同样的配置下,linux (32 位)平台上的到的结果都远大于 windows 平台,但所得到的最终结果并没错,即:glibc 实现的 malloc 同时使用 brk 和 mmap 两个系统调用获取内存,对于大块内存优先使用 mmap.其他 C 库则取决与其 malloc 函数的具体实现。之前看过一篇文章说,windows 的底层是符合 POSIX 的,求高人证实。
2012/3/18
#include
#include
int main()
{
int size = 0;
while (sbrk(1 << 20) != (void *)-1)
size++;
printf ("heap max size is %d MBn", size);
return 0;
}
heap max size is 383 MB
#include
#include
int main()
{
int size = 0;
void *p;
while ((p = malloc(1 << 20)))
{
size++;
if (!(size % 100))
printf("%dMBt 0x%.8xn", size, (unsigned int)p);
}
printf("nmax malloc memory size is %d MBn", size);
return 0;
}
100MB 0x79420008
200MB 0x72280008
300MB 0x6b840008
400MB 0x64e00008
500MB 0x5ded0008
600MB 0x57490008
700MB 0x50a50008
800MB 0x4a010008
900MB 0x435d0008
1000MB 0x3cb90008
1100MB 0x36150008
1200MB 0x2f710008
1300MB 0x28cd0008
1400MB 0x22290008
1500MB 0x1b850008
1600MB 0x043e03d8
1700MB 0x0a7e06f8
1800MB 0x10be0a18
1900MB 0x16fe0d38
max malloc memory size is 1925 MB
#include
#include
#include
#include
int main()
{
int size = 0;
while (mmap(NULL, 1 << 20, PROT_READ, MAP_PRIVATE|MAP_ANON,
0, 0) != (void *)-1)
size++;
printf ("mmap max size is %d MBn", size);
return 0;
}
mmap max size is 1641 MB
/* ...
Rather than using a static threshold for the brk/mmap tradeoff,
we are now using a simple dynamic one. The goal is still to avoid
fragmentation. The old goals we kept are
1) try to get the long lived large allocations to use mmap()
2) really large allocations should always use mmap()
and we're adding now:
3) transient allocations should use brk() to avoid forcing the kernel
having to zero memory over and over again
... */
#include
#include
void *mmap (void *addr, size_t length, int prot, int flags, int fd, off_t offset);
int munmap(void *addr, size_t length);
联系客服