Skip to content

Instantly share code, notes, and snippets.

@hartwork
Last active January 2, 2022 00:20
Show Gist options
  • Save hartwork/5688d1bd4f2ec63c0094bce6f2303e4b to your computer and use it in GitHub Desktop.
Save hartwork/5688d1bd4f2ec63c0094bce6f2303e4b to your computer and use it in GitHub Desktop.
// Copyright (c) 2021 Sebastian Pipping <sebastian@pipping.org>
// Licensed under the Apache license version 2.0
//
// Compile and run with:
// # gcc -std=gnu99 -Wall -Wextra -pedantic bisect_malloc.c && ./a.out
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
const struct timespec sleepFor = {.tv_sec = 0, .tv_nsec = 125 * 1000 * 1000};
size_t left = 0;
size_t right = (size_t)-1;
bool firstRound = true;
for (;;) {
const size_t candidate = firstRound ? right : (left / 2 + right / 2);
if (candidate == left) {
break;
}
printf("Trying to allocate %21zu bytes... ", candidate);
void *const malloced = malloc(candidate);
if (malloced) {
printf("PASS\n");
free(malloced);
left = candidate;
} else {
printf(" FAIL\n");
if (!firstRound) {
right = candidate;
}
}
nanosleep(&sleepFor, NULL);
firstRound = false;
}
printf("\nDone, biggest success was %zu bytes.\n", left);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment