Search code examples
clinuxmemorymemory-managementheap-memory

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.


Solution

  • 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