Created
September 30, 2026 14:48
-
-
Save hartwork/f6c0f833859fab0b7cd1be960eac6991 to your computer and use it in GitHub Desktop.
Determine the amount of RAM that can be allocated in practice
This file contains hidden or 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) 2026 Sebastian Pipping <sebastian@pipping.org> | |
| // Licensed under the Apache license version 2.0 | |
| // | |
| // Compile and run with: | |
| // # gcc -std=c99 -Wall -Wextra -Werror useram.c && ./a.out malloc | |
| #include <assert.h> | |
| #include <limits.h> | |
| #include <locale.h> | |
| #include <stdbool.h> | |
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <string.h> | |
| static void usage(const char *progname) { | |
| fprintf(stderr, "usage: %s (malloc|calloc|memset)\n", progname); | |
| } | |
| int main(int argc, char **argv) { | |
| if (argc != 2) { | |
| usage(argv[0]); | |
| return 1; | |
| } | |
| bool use_calloc = false; | |
| bool use_memset = false; | |
| if (strcmp(argv[1], "calloc") == 0) { | |
| use_calloc = true; | |
| } else if (strcmp(argv[1], "memset") == 0) { | |
| use_memset = true; | |
| } else if (strcmp(argv[1], "malloc") == 0) { | |
| // no-op | |
| } else { | |
| usage(argv[0]); | |
| return 1; | |
| } | |
| const size_t chunk = 500 * 1024 * 1024; // 500 MiB | |
| unsigned long long totalAllocated = 0; | |
| setlocale(LC_NUMERIC, ""); | |
| while (true) { | |
| printf("%'19llu\n", totalAllocated); // math.ceil(math.log10(2**63)) == 19 | |
| void *const buffer = use_calloc ? calloc(1, chunk) : malloc(chunk); | |
| if (buffer == NULL) { | |
| printf("NULL returned.\n"); | |
| return 0; | |
| } | |
| if (use_memset) | |
| memset(buffer, 'X', chunk); | |
| if (chunk > ULLONG_MAX - totalAllocated) { | |
| printf("Integer overflow at >%llu bytes.\n", ULLONG_MAX); | |
| return 0; | |
| } | |
| totalAllocated += chunk; | |
| } | |
| assert(false); | |
| return 1; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment