6

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?

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Attempting to set rlimit_stack after Stack Clash remediations may result in failure or related problems. Also see Red Hat Issue 1463241
3

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); }

6 Comments

Your initialization of rl is invalid; it assumes a particular ordering of elements. You need to either use C99 designated initializers, or just assign to the elements by name as independent statements.
When you run out of memory, doesn't the OS swap them on disk?
@MickeyShine: That's a very different type of memory. You should read up about virtual memory in modern OS design! :-)
@R.: I lifted this from some C++ code of mine. What should it be in C? Feel free to edit! Edit: I "fixed" it ;-)
That's still not valid if the structure happens to have extra members. Valid would be: struct rlimit rl = { .rlim_cur = 32000, .rlim_max = 32000 }; ... Also notice the necessity of the struct keyword.
|
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.