/** bigmallocer v. 2.1  --  allocate a huge portion of memory 
  *                         and wait for being killed
  * Copyright (C) 2008 Jannis A. Schnitzer
  * 
  * invocation: bigmallocer   --  allocates the default amount of memory
  *                               (see definitions below)
  *             bigmallocer [number]  --  allocate [number] MB of memory
  * 
  * This program is free software; you can redistribute it and/or modify        
  * it under the terms of the GNU General Public License as published by        
  * the Free Software Foundation; either version 2 of the License, or           
  * (at your option) any later version.                                         
  *                                                                             
  * This program is distributed in the hope that it will be useful,             
  * but WITHOUT ANY WARRANTY; without even the implied warranty of              
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the               
  * GNU General Public License for more details.                                
  *                                                                             
  * You should have received a copy of the GNU General Public License           
  * along with this program; if not, write to the                               
  * Free Software Foundation, Inc.,                                             
  * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.                   
  */

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

#define MEGABYTE (1024*1024)
#define LOGSIZE  (10)
#define DEFAULT  786
#define SIZE_MAX 4096

int printsize(int i)
{
    (void)printf("\b\b\b\b\b\b\b\b\b%6d MB", i);
    fflush(NULL);
    return 1;
}

int main(int argc, char **argv)
{
    const int PAGESIZE = getpagesize();
    char **buffer;
    int size, pages;
    if (argc > 1)
        size = atoi(argv[1]);
    if (size < 1 || size > SIZE_MAX)
        size = DEFAULT;
    pages = size * ((float)MEGABYTE/PAGESIZE);
    printf("pages: %d\n", pages);
    
    buffer = (char**)malloc(pages*sizeof(char*));
    if (!buffer)
    {
        return 1;
    }
    else
    {
        int i;
        for (i = 0; i < pages; i++)
        {
            buffer[i] = (char*)malloc(PAGESIZE);
            buffer[i][0] = 'x';
            (i % LOGSIZE) || printsize(i*((float)PAGESIZE/MEGABYTE));
        }
        printsize(i*((float)PAGESIZE/MEGABYTE));
        printf ("\nDone.\n");
        while (1)
        {
            sleep(60);
        }
    }
    return 0;
}
