编写C程序时如何设置内存使用限制以及一旦超过此限制会发生什么?
我正在Linux上编写C程序,我想知道:
如何限制我的C程序消耗的总内存?
如果我为我的 C 程序设置内存限制,比如 32M,如果它需要的内存远多于 32M,会发生什么?
I am writing a C program on linux and I wonder:
How to limit the total memory my c program consumes?
If I set a memory limit to my c program, say 32M, what happens if it requires much more memory than 32M?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该使用 setrlimit 系统调用以及 RLIMIT_DATA 和 RLIMIT_STACK 资源来分别限制堆和堆栈大小。使用 RLIMIT_AS 或 RLIMIT_RSS 很诱人,但您会发现它们在许多旧的 Linux 内核上不能可靠地工作,而且我在内核邮件列表上没有看到任何迹象表明问题已在最新内核中得到解决。一个问题涉及如何对 mmap 内存进行计数,或者更确切地说,如何不将其计入限制总数。由于 glibc malloc 使用 mmap 进行大量分配,因此即使不直接调用 mmap 的程序也可能会超出限制。
如果超出 RLIMIT_STACK 限制(调用堆栈太深,或在堆栈上分配太多变量),您的程序将收到 SIGSEGV。如果您尝试将数据段扩展至超过 RLIMIT_DATA 限制(brk、sbrk 或某些中介(如 malloc)),则尝试将失败。 brk 或 sbrk 将返回 < 0 和 malloc 将返回空指针。
You should use the setrlimit system call, with the RLIMIT_DATA and RLIMIT_STACK resources to limit the heap and stack sizes respectively. It is tempting to use RLIMIT_AS or RLIMIT_RSS but you will discover that they do not work reliably on many old Linux kernels, and I see no sign on the kernel mailing list that the problems have been resolved in the latest kernels. One problem relates to how mmap'd memory is counted or rather not counted toward the limit totals. Since glibc malloc uses mmap for large allocations, even programs that don't call mmap directly can exceed the limits.
If you exceed the RLIMIT_STACK limit (call stack too deep, or allocate too many variables on the stack), your program will receive a SIGSEGV. If you try to extend the data segment past the RLIMIT_DATA limit (brk, sbrk or some intermediary like malloc), the attempt will fail. brk or sbrk will return < 0 and malloc will return a null pointer.
在 Linux 上,在 C 程序中,使用
setrlimit()
设置程序的执行环境限制。例如,当内存不足时,调用malloc()
将返回 NULL 等。On Linux, within your C program, use
setrlimit()
to set your program's execution environment limits. When you run out of memory, for instance, then calls tomalloc()
will return NULL etc.请参阅系统中的
ulimit
命令。来自
man
页:如果您的程序编写得好,它应该考虑动态内存分配失败的情况:检查
malloc
、calloc 的返回值
和realloc
函数。See
ulimit
command in your system.From the
man
page:If your program is well-written it should take of the cases where a dynamic memory allocation fails: check the return value of
malloc
,calloc
andrealloc
functions.