C – How to limit the heap size of C code in Linux

How to limit the heap size of C code in Linux… here is a solution to the problem.

How to limit the heap size of C code in Linux

I was wondering if it was possible to limit the heap size allocated by C code executed on linux machines.

Is it possible?

The purpose of this is that I dynamically allocated ~70KBytes memory and ~20KBytes stack memory in addition to other global and local variables. Dynamic allocation is done via malloc().

So, to confirm that the

problem isn’t with heap allocation, I want to limit the heap memory of the C code that will be run.

I’ve read some articles online and found that if we use malloc(), the memory can be overused, but if we use calloc(), we will only get the available memory and not overused because calloc() must initialize to zero out the memory block before giving a pointer. But I don’t want to use calloc() because of initialization overhead.

Solution

You can use (in your program) setrlimit(2), which may differ from RLIMIT_AS (by Ouah’s answer quote).

Better yet, let your shell do this. For bash, it’s the built-in ulimit.

Make sure that your program has indeed handled malloc failures correctly and completely everywhere (testing whether each return value of malloc matches NULL to indicate its failure).

If you don’t test the results of malloc, when it fails, it will give NULL and the next instruction will most likely dereference a null pointer (or some address very close to it), ie undefined behavior is given on Linux segmentation violation .

You should probably consider using valgrind during the debugging phase.

By the way, 70KB of memory is already small today (at least on Linux laptops, desktops, and even tablets). Note that C standard library can call malloc behind the scenes (e.g., fopen Given a FILE handle, it has some buffers that can be obtained internally >malloc).

andmemory overcommit can be disabled on Linux using the following command

echo 0 > /proc/sys/vm/overcommit_memory

Run as root.

Related Problems and Solutions