#include #include #include #define A_MEGABYTE (1024 * 1024) #define PHY_MEM_MEGS 256 /* Adjust this number as required */ int main() { char *some_memory; size_t size_to_allocate = A_MEGABYTE; int megs_obtained = 0; while (megs_obtained < (PHY_MEM_MEGS * 2)) { some_memory = (char *)malloc(size_to_allocate); if (some_memory != NULL) { megs_obtained++; sprintf(some_memory, “Hello World”); printf(“%s - now allocated %d Megabytes\n”, some_memory, megs_obtained); } else { exit(EXIT_FAILURE); } } exit(EXIT_SUCCESS); }
程序会产生类似于下面的输出:
$ ./memory2 Hello World - now allocated 1 Megabytes Hello World - now allocated 2 Megabytes ... Hello World - now allocated 511 Megabytes Hello World - now allocated 512 Megabytes