Skip to content

Instantly share code, notes, and snippets.

@acdha
Created April 3, 2009 21:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acdha/89976 to your computer and use it in GitHub Desktop.
Save acdha/89976 to your computer and use it in GitHub Desktop.
A simple utility to determine the largest allocation possible for your operating system, compiler and C library
/*
* MaxMalloc: a simple test to determine the maximum memory allocation
*
* gcc -Os -Wall -Wextra -o maxmalloc maxmalloc.c
*/
#include <getopt.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
void usage(const char *executable) {
printf("Usage: %s [-m] [-b block_size] [-s small_block_size]\n\t-m: use memset to confirm that allocated memory is actually usable (SLOW!)\n\t-b: set the block size increment used to determine the largest single allocation (0=disable)\n\t-s: set the block size used to determine the largest cumulative allocation (0=disable)\n", executable);
exit(0);
}
int main(int argc, char *argv[]) {
int do_memset = 0;
unsigned long block_size = 65536L;
unsigned long small_block_size = 1024L;
void *p;
char opt;
while ((opt = getopt(argc, argv, "b:s:m")) != -1) {
switch (opt) {
case 'b':
sscanf(optarg, "%lu", &block_size);
break;
case 's':
sscanf(optarg, "%lu", &small_block_size);
break;
case 'm':
do_memset = 1;
break;
default:
usage(argv[0]);
}
}
if (block_size > 0) {
#ifdef USE_GOOD_SIZE
block_size = malloc_good_size(block_size);
#endif
printf("Determining maximum single allocation: block size = %lu, memset=%d\n", block_size, do_memset);
unsigned long blocks = 0;
while ( (p = malloc( blocks * block_size )) != NULL) {
if (do_memset) memset(p, 0, blocks * block_size);
free(p);
blocks++;
}
printf("Maximum single allocation: %0.2fGb (%lu %lu blocks)\n", (float)(blocks * block_size) / 1073741824, blocks, block_size);
}
if (small_block_size > 0) {
#ifdef USE_GOOD_SIZE
small_block_size = malloc_good_size(small_block_size);
#endif
printf("Determining maximum allocation size: small block size = %lu, memset=%d\n", small_block_size, do_memset);
unsigned long malloc_highwater = 0;
while ((p = malloc(small_block_size)) != NULL ) {
malloc_highwater += small_block_size;
if (do_memset) memset(p, 0, malloc_highwater);
}
printf("Maximum total allocation: %0.2fGb (%lu %lu blocks)\n", (float)(malloc_highwater / 1073741824), malloc_highwater / small_block_size, small_block_size);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment