This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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