3

So I've learned that its hella easy to make a memory leak in C :

#include <stdio.h>
void main() {
    int* p;
    int i=0;
    
    p=(int*)malloc(sizeof(int));
    while (p!=NULL) {
        p=(int*)malloc(sizeof(int));
        i++;
    }
    printf("malloc failed after %d allocations\n",i);
}

And I wanted to see how I could avoid restarting my computer every time I launch this program (or just kill it before its too late).

ulimit seems to be the solution. ulimit -S -m 1000000 should prevent any process to take more than 1000000 kbyte / 1gbyte of memory (I have a 32gbyte of RAM). But it seems to have absolutely no effect: when I launch the program above, it will use all of the memory if I don't kill it.

I tried setting a very low limit (100 kbyte...), or set a virtual memory limit (-v) instead of RSS but no effects were seen...

What did I miss?

3
  • -S sets a "soft" limit, which is advisory. Use ulimit -H to set a hard (enforced) limit for your process.
    – waltinator
    Nov 24, 2020 at 17:48
  • Soft means it is ignored ? With the -H option I get ulimit: max memory size: cannot modify limit: Invalid argument
    – sayanel
    Nov 24, 2020 at 19:20
  • 1
    "Soft" means that the limit can later be increased; "hard" that it can only be further reduced. May 23, 2023 at 13:17

2 Answers 2

3

ulimit -m limits the resident set size of the process - i.e. how much of the process may be paged in at one time.

If you have swap available, the process's virtual memory can be much larger.

ulimit -v limits the amount of virtual memory that may be allocated, and that's what you want. Note that it's not necessarily inherited by child processes, so use a subshell and exec:

( ulimit -v 1000000 && exec test_program )
2
  • This do work ! After 3 years I have my answer, thanks ! Note that (on mint 21), it do work without subshell (ulimit -v 1000; ./test_program;). But if I set ulimit -v 100 alone, then I can't increase this value later on this shell (operation not permitted), which is weird.
    – sayanel
    May 28, 2023 at 7:09
  • 1
    POSIX allows, but does not require that subprocesses inherit the limit (so you might not need exec on your system, but you can't assume so in a portable program). Using a subshell anyway is a good idea to avoid constraining your shell permanently in the way you discovered. Apr 4 at 8:36
-2

Ram (on most Unix systems) is lazily allocated on first write. You don't write to the pointer you get back from malloc().

1
  • Well, I got the desired output ("malloc failed...") with Toby answer, so it's not that
    – sayanel
    May 28, 2023 at 7:02

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .