问题描述
我有一个C Linux应用程序,该应用程序使用malloc,calloc,realloc和amp;持续分配和释放内存(每秒约200个分配/空闲).免费功能.即使所有分配的内存都已释放(通过包装* alloc和free进行验证),VmSize,VmRSS& VmData的数量不断增加,最终应用程序被OOM杀手杀死.
I have C Linux application which continuously allocates and frees memory (around 200 alloc/free per sec) using malloc, calloc, realloc & free functions. Even though all allocated memory are freed (verified by wrapping *alloc and free), the VmSize, VmRSS & VmData numbers are keep on increasing and finally application is getting killed by OOM killer.
为什么要使用VmSize,VmRSS& VmData是否一直在增加?如果是内存管理问题,是否有避免这种情况的指针?
Why the VmSize, VmRSS & VmData are keep on increasing? if it is Memory management issue, any pointers to avoid this?
我看到了这个 C中的问题使用内存,但是答案并没有解释OOM行为.
I saw this Problem usage memory in C, but the answers are not explaining the OOM behavior.
推荐答案
您应首先使用 valgrind (进行调试可能很难找到内存泄漏或行为异常).不要忘记使用gcc -Wall -g
进行编译(然后,在工作时使用-Wall -O
);当然,请改进代码,直到没有任何警告.
You should first use valgrind (to debug potential hard to find memory leaks or misbehavior). Don't forget to compile with gcc -Wall -g
(then, when it works, use -Wall -O
); of course, improve your code till no warnings are given.
您可能(如果算法合适)尝试(有用)分配例如2的幂或3的幂的三倍[也许减去2或3个单词];至少要避免分配太多不同的随机大小.
You could probably (if the algorithms fit) try to (usefully) allocate memory zone of e.g. either power of two, or 3 times a power of two [perhaps minus 2 or 3 words]; at least try to avoid too many different random sizes of allocation.
您可能要尝试使用 Boehm的保守垃圾收集器-即将所有malloc
替换为GC_MALLOC
(或将GC_MALLOC_ATOMIC
& strdup
替换为GC_STRDUP
),将free
替换为GC_FREE
,依此类推
You may want to try using Boehm's conservative garbage collector - i.e. replacing all your malloc
with GC_MALLOC
(or GC_MALLOC_ATOMIC
& strdup
with GC_STRDUP
), your free
with GC_FREE
, etc...
至少出于测试目的,请使用 setrlimit(2)可能是通过内置的 ulimit 内置的.您想要RLIMIT_AS
-可能与RLIMIT_DATA
(设置这些限制可以避免OOM杀手,并使mmap
-由malloc
调用的-在内存耗尽时失败).
At least for testing purposes, use setrlimit(2) perhaps thru the bash ulimit builtin. You want RLIMIT_AS
- possibly with RLIMIT_DATA
(setting these limits sensibly avoids the OOM killer and makes your mmap
-called by malloc
- fail when memory is exhausted).
您可能希望使用接受 -fsanitize = address .
您还可以实现自己的特定于应用程序的垃圾收集器(请阅读Wikipage,它为您提供见解和术语); 标记&紧凑算法将对抗碎片化.
You could also implement your own application specific garbage collector (read that wikipage, it gives you insights and terminology); a mark & compact algorithm will fight fragmentation.
这篇关于Linux c应用程序内存使用情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!