Q:

How many times could I run this program

I have a machine with 128M memory, and this is the program.
while(1)
{    
    ptr = malloc(1024 * 1024 * 100);
    if (NULL == ptr)
    {
        printf("malloc 100M Failed\n");
       return 1;
    }
    n+=100;
    printf("malloc %dM\n", n);
}

I found from output that malloc run 20 times, why?

A:

Because your program is allocating virtual memory. In a 32-bit process (on Windows - other operating systems are slightly different), you typically get 2GB of virtual address space in which to allocate memory. The operating system them maps that memory between a "swap file" and physical memory (in your case, since you only have 128MB of physical memory, the majority of the memory you allocate will be in the swap file only).
So 100MB * 20 = "around" 2GB, and that explains why you can run through 20 loops.

