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

long malloc_count = 0;

void fail(char *s)
{
    puts(s);
    printf("Total Number of Calls to malloc(): %d\n",malloc_count);
    exit(1);
}

main(int argc, char *argv[])
{
    char *p;
    unsigned meg;
    unsigned long maxallocs;
    unsigned long allocs;

    if (argc < 2)
        meg = 1;                // default 1 megabyte  required 
    else
        meg = atoi(argv[1]);    // command-line option:  n megabytes 

    printf("Allocating %u megabyte%s...  ",meg, (meg > 1) ?  "s" : "");
    printf("\n");

    maxallocs = ((long)meg) << 10;  // number of 1k blocks required 

    for (allocs = 0; allocs < maxallocs; allocs++)
    {
        if (p = malloc(1024))   // in 1k blocks 
        {
            malloc_count++;
            *p = 'x';       // do something with the memory
            p[1023] = 'y';
        }
        else
        {
            printf("Only %lu bytes available\n", allocs << 10);
            fail("Insufficient memory!");
        }
    }
    printf("Total Number of Calls to malloc(): %d\n",malloc_count);
    return 0;
} 
