使用malloc的内存泄漏失败 [英] Memory Leak Using malloc fails
问题描述
我正在向泄漏内存(主内存)编写一个程序,以测试系统在低系统内存和交换内存的情况下的行为.我们正在使用以下循环,该循环定期运行并泄漏内存
main(int argc, char* argv[] )
{
int arg_mem = argv[1];
while(1)
{
u_int_ptr =(unsigned int*) malloc(arg_mem * 1024 * 1024);
if( u_int_ptr == NULL )
printf("\n leakyapp Daemon FAILED due to insufficient available memory....");
sleep( arg_time );
}
}
以上循环运行一段时间,并显示消息由于可用内存不足,导致leakyapp守护程序失败...".但是,当我运行命令"free"时,我可以看到运行该程序对主存或交换都没有影响.
我做错什么了吗?
物理内存只有在您实际写入内存后才会提交给您.
如果内核版本为2.6.23之后,请使用带有MAP_POPULATE
标志而不是malloc()
的mmap()
:
u_int_ptr = mmap(NULL, arg_mem * 1024 * 1024, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_POPULATE, -1, 0);
if (u_int_ptr == MAP_FAILED)
/* ... */
如果您的内核较旧,则必须触摸分配中的每个页面.
I am writing a program to leak memory( main memory ) to test how the system behaves with low system memory and swap memory. We are using the following loop which runs periodically and leaks memory
main(int argc, char* argv[] )
{
int arg_mem = argv[1];
while(1)
{
u_int_ptr =(unsigned int*) malloc(arg_mem * 1024 * 1024);
if( u_int_ptr == NULL )
printf("\n leakyapp Daemon FAILED due to insufficient available memory....");
sleep( arg_time );
}
}
Above loop runs for sometime and prints the message "leakyapp Daemon FAILED due to insufficient available memory...." . But when I run the command "free" I can see that running this program has no effect either on Main memory or Swap.
Am I doing something wrong ?
Physical memory is not committed to your allocations until you actually write into it.
If you have a kernel version after 2.6.23, use mmap()
with the MAP_POPULATE
flag instead of malloc()
:
u_int_ptr = mmap(NULL, arg_mem * 1024 * 1024, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_POPULATE, -1, 0);
if (u_int_ptr == MAP_FAILED)
/* ... */
If you have an older kernel, you'll have to touch each page in the allocation.
这篇关于使用malloc的内存泄漏失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!