// // pirate -- Take what you can, give nothing back (a malloc test). // // 05-Sep-2009 tvb & Nvb & Tvb www.LeapSecond.com // // Note: September 19th is Talk Like A Pirate Day (www.talklikeapirate.com) // #include #include #include char *bytes_i (long size); char *bytes_f (double size); int main (int argc, char *argv[]) { long count, size; int fill_byte; void *p; double total_bytes; fill_byte = (argc > 1) ? atoi(argv[1]) : 0; printf("pirate: take what you can, give nothing back!\n"); total_bytes = 0.0; for (size = 64 * 1024 * 1024; size > 0; size /= 2) { count = 0; while (NULL != (p = malloc(size))) { count += 1; // Show progress so far. printf(" arrgh, we got us %s more (x %ld = %s)!%s", bytes_i(size), count, bytes_f(size * (double)count), " \r"); // Fill (commit), if requested. if (fill_byte != 0) { memset(p, fill_byte, size); } // free(p); give nothing back } // Delay a quarter second for visual effect. #ifdef _WIN32 _sleep(200); #else usleep(200*1000); #endif total_bytes += size * (double)count; if (count != 0) { printf("\n"); } else { printf(" avast, aint no %s to be found, me hearties!\n", bytes_i(size)); } } printf("pirate: we got all yer filthy memory (%s), savvy? [yn]", bytes_f(total_bytes)); getchar(); return 0; } char *bytes_i (long size) { static char buf[100]; if (size >= 1024 * 1024) { sprintf(buf, "%ld MB", size / (1024 * 1024)); } else if (size >= 1024) { sprintf(buf, "%ld KB", size / 1024); } else { sprintf(buf, "%ld byte%s", size, size == 1 ? "" : "s"); } return buf; // WARNING: static } char *bytes_f (double size) { static char buf[100]; if (size >= 1024.0 * 1024.0) { sprintf(buf, "%.3lf MB", size / (1024.0 * 1024.0)); } else if (size >= 1024.0) { sprintf(buf, "%.3lf KB", size / 1024.0); } else { sprintf(buf, "%.0lf byte%s", size, size == 1.0 ? "" : "s"); } return buf; // WARNING: static }