From C
/* For use with C89 */
#include <stddef.h>
#include <stdlib.h>
static void * biggest_buf(void);
int main(void) {
char * foo, * bar, * baz;
foo = biggest_buf();
bar = biggest_buf();
baz = biggest_buf();
free(foo);
free(bar);
free(baz);
return EXIT_SUCCESS;
}
static void * biggest_buf(void) {
char * big_buf;
size_t max_size, big_size, test_size, highest_test;
/* Find the maximum size_t */
max_size = 0;
--max_size;
switch (0) while (1) {
/* big_size < test_size < highest_test */
big_buf = malloc(test_size);
if (!big_buf) {
if (test_size == big_size) {
/* Maximum allocation has changed. Start over */
default:
test_size = highest_test = max_size;
big_size = 0;
continue;
}
/*
* We couldn't allocate a bigger buffer than last time.
* Split the difference and try a smaller allocation
*/
highest_test = test_size;
test_size = (test_size - big_size) / 2 + big_size;
continue;
}
/* Check if we've found the biggest allocation */
if (test_size == big_size) {
/* All done */
break;
}
/* Otherwise, we might be able to allocate more */
free(big_buf);
big_size = test_size;
test_size = (highest_test - big_size) / 2 + big_size;
continue;
}
return big_buf;
}