sunny
sunny

Reputation: 43

How to limit heap size for a c code in linux

I wanted to know if it is possible to limit the allocated heap size for a C code which is executing on linux machine.

Is it possible to do so ?

The purpose of doing so is that I am dynamically allocating ~70KBytes of memory and ~20KBytes of stack memory, apart from other globals, and locals. The dynamic allocation is done through malloc().

So in order to confirm that the issue is not with the heap allocation, I want to limit the heap memory of the C code which will be run.

I read few articles online and found that if we use malloc(), memory might be over committed, but if we use calloc(), we will get only usable memory without the over commitment, since calloc() has to initialize the memory block to zeros before giving the pointer. But I do not want use calloc() due to the initialization overhead.

Upvotes: 4

Views: 4164

Answers (2)

You could use (inside your program) setrlimit(2), probably with RLIMIT_AS (as cited by Ouah's answer).

Better yet, make your shell do it. With bash it is the ulimit builtin.

Be sure that your program is indeed correctly and completely handling malloc failure everywhere (testing every return of malloc against NULL indicating its failure).

If you don't test malloc's result, when it is failing, it gives NULL and it is very likely that the next instructions would dereference a null pointer (or some address very close to it), which is undefined behavior and on Linux giving a segmentation violation.

You probably should consider using valgrind during the debugging phase.

BTW, 70Kilobytes of memory is tiny today (at least on Linux laptops, desktops and even tablets). Notice that the C standard library may call malloc under the hoods (for example, fopen gives a FILE handle, which has some buffer, which might be internally obtained thru malloc)

And memory overcommit can be disabled on Linux with the following command

echo 1 | sudo tee  /proc/sys/vm/overcommit_memory

Upvotes: 4

ouah
ouah

Reputation: 145829

On POSIX systems you can use setrlimit function to limit the size of the virtual memory of the process.

From POSIX documentation:

RLIMIT_AS

This is the maximum size of total available memory of the process, in bytes. If this limit is exceeded, the malloc() and mmap() functions shall fail with errno set to [ENOMEM]. In addition, the automatic stack growth fails with the effects outlined above.

Upvotes: 1

Related Questions