编写C程序时如何设置内存使用限制以及一旦超过此限制会发生什么?

发布于 2025-01-03 07:28:06 字数 138 浏览 0 评论 0原文

我正在Linux上编写C程序,我想知道:

  1. 如何限制我的C程序消耗的总内存?

  2. 如果我为我的 C 程序设置内存限制,比如 32M,如果它需要的内存远多于 32M,会发生什么?

I am writing a C program on linux and I wonder:

  1. How to limit the total memory my c program consumes?

  2. If I set a memory limit to my c program, say 32M, what happens if it requires much more memory than 32M?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

掐死时间 2025-01-10 07:28:06

您应该使用 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.

月牙弯弯 2025-01-10 07:28:06

在 Linux 上,在 C 程序中,使用 setrlimit()设置程序的执行环境限制。例如,当内存不足时,调用 malloc() 将返回 NULL 等。

#include <sys/resource.h>

{ struct rlimit rl = {32000, 32000}; setrlimit(RLIMIT_AS, &rl); }

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 to malloc() will return NULL etc.

#include <sys/resource.h>

{ struct rlimit rl = {32000, 32000}; setrlimit(RLIMIT_AS, &rl); }
碍人泪离人颜 2025-01-10 07:28:06

请参阅系统中的 ulimit 命令。

来自 man 页:

-v   The maximum amount of virtual memory available to the process

如果您的程序编写得好,它应该考虑动态内存分配失败的情况:检查 malloccalloc 的返回值realloc 函数。

See ulimit command in your system.

From the man page:

-v   The maximum amount of virtual memory available to the process

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 and realloc functions.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文