tags:

views:

420

answers:

5
+8  Q: 

Reserve RAM in C

Hi

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?

+3  A: 

Can't you just use malloc() to allocate that ram to your process? That will reserve that RAM for you, and then you are free to do whatever you wish with it.

Here's an example for you:

#include <stdlib.h>
int main (int argc, char* argv[]) {
    int bytesToAllocate;
    char* bytesReserved = NULL;

    //assume you have code here that fills bytesToAllocate

    bytesReserved = malloc(bytesToAllocate);
    if (bytesReserved == NULL) {
        //an error occurred while reserving the memory - handle it here
    }

    //when the program ends:
    free(bytesReserved);

    return 0;
}

If you want more information, have a look at the man page (man malloc in a linux shell). If you aren't on linux, have a look at the online man page.

a_m0d
It might be that dynamic allocation is new to this guy... You should really explain it, or at least provide a link to a decent tutorial.
Platinum Azure
@PlatinumAzure - Done
a_m0d
This seems to be a great framework for the final application.
petersmith221
Also, as Tim Post points out, malloc isn't always enough. The memory may not really be reserved until you actually write to it, for instance.
Steve314
@Steve314 - Apparently, malloc will not allocate physical memory, but it will ensure that there is enough virtual memory allocated. That should still show up in a resource manage, AFAIK.
a_m0d
@a_m0d: Awesome, thanks. +1
Platinum Azure
+15  A: 

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

  1. Write data to the memory so that the kernel actually guarantees it. You can use memset() for this.
  2. Prevent the memory from being paged out (swapped), the mlock() / mlockall() functions can help you with this.
  3. 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.

Tim Post
Very comprehensive answer.
Steven Sudit
I found the POSIX Programmer's Manual when checking up on the functions you mentions, i think that this will be useful to me also.
petersmith221
For those that are wondering; unless you use the memory you requested, the kernel may kill your process and give the memory to another process that has requested memory. This is called *overcommit*.
dreamlax
dreamlax - Thanks for the info, i just learned the overcommit percentage on my system and found info about vm.overcommit_memory, i did not know about that before
petersmith221
You can disable overcommit by typing (as root) into a shell: `echo 2 > /proc/sys/vm/overcommit_memory`
a_m0d
+1 for mlock() / mlockall(). Make sure to write to memory so that memory is actually claimed..
Jack
A: 

You will need:

  • malloc() to allocate however many bytes you need (malloc(200000000) or malloc(20 * (1 << 20))).
  • getc() to wait for a keypress.
  • free() to deallocate the memory.

The information on these pages should be helpful.

Matt J
It is actually to check the resource manager in a cluster so a job will be run when x MB of RAM is free on a node. But i am trying to learn C when i am not working with clusters, so therefore i posted the question here so i can try the different ideas and solutions and learn new parts of C at the same time.
petersmith221
if you want to know how much memory is free you should definitely be using /proc/vmstat and not just testing for malloc failure.
Ben Voigt
@petersmith221: Rock on, good philosophy.@Matt J: Apologies for hijacking a comment just for that address to the original poster's comment. :-)
Platinum Azure
+1  A: 

calloc() is what you want. It will reserve memory for your process and write zero's to it. This ensures that the memory is actually allocated for your process. If you malloc() a large portion of memory, the OS may be lazy about actually allocating memory for you, only actually allocating it when it is written to (which will never happen in this case).

jdizzle
A: 

Did this, should work. Although I was able to reserve more RAM than I have installed, this should work for valid values, tho.

#include <stdio.h>
#include <stdlib.h>

enum
{
   MULTIPLICATOR = 1024 * 1024 // 1 MB
};


int
main(int argc, char *argv[])
{
   void *reserve;
   unsigned int amount;

   if (argc < 2)
   {   
      fprintf(stderr, "usage: %s <megabytes>\n", argv[0]);
      return EXIT_FAILURE;
   }   

   amount = atoi(argv[1]);

   printf("About to reserve %ld MB (%ld Bytes) of RAM...\n", amount, amount * MULTIPLICATOR);

   reserve = calloc(amount * MULTIPLICATOR, 1);
   if (reserve == NULL)
   {   
      fprintf(stderr, "Couldn't allocate memory\n");
      return EXIT_FAILURE;
   }   

   printf("Allocated. Press any key to release the memory.\n");

   getchar();
   free(reserve);
   printf("Deallocated reserved memory\n");

   return EXIT_SUCCESS;
}
LukeN