Reserve RAM in C

c, linux, memory, ram

Solution

You want to use malloc() to do this. Depending on your need, you will also want to:

- Write data to the memory so that the kernel actually guarantees it. You can use memset() for this.

- Prevent the memory from being paged out (swapped), the mlock() / mlockall() functions can help you with this.

- Tell the kernel how you actually intend to use the memory, which is accomplished via posix_madvise() (this is preferable to an explicit mlockall()).

In most realities, malloc() and memset() (or, calloc() which effectively does the same) will suit your needs.

Finally, of course, you want to free() the memory when it is no longer needed.

Problem

I need ideas on how to write a C program that reserve a specified amount of MB RAM until a key [ex. the any key] is pressed on a Linux 2.6 32 bit system. ``` * /.eat_ram.out 200 # If free -m is execute at this time, it should report 200 MB more in the used section, than before running the program. [Any key is pressed] # Now all the reserved RAM should be released and the program exits. * ``` It is the core functionality of the program [reserving the RAM] i do not know how to do, getting arguments from the commandline, printing [Any key is pressed] and so on is not a problem from me. Any ideas on how to do this?

Original source