Mickey Shine
Mickey Shine

Reputation: 12559

How to set memory use limit when writing C program and what happens if once it exceeds this limit?

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?

Upvotes: 6

Views: 8624

Answers (3)

Kyle Jones
Kyle Jones

Reputation: 5532

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.

Upvotes: 5

Kerrek SB
Kerrek SB

Reputation: 477640

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

Upvotes: 3

ouah
ouah

Reputation: 145919

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.

Upvotes: 2

Related Questions