From 1414a5667339637ca815dee52a527abb9bcfc528 Mon Sep 17 00:00:00 2001 From: Nicholas Tay Date: Thu, 13 Jan 2022 23:19:28 +1100 Subject: Use static buffers for regular password generation This is probably a micro-optimisation, but since that is partly the point of this random C project, let's do it :) --- config.h | 3 +++ passgen.c | 38 ++++++++++++++++++++++---------------- 2 files changed, 25 insertions(+), 16 deletions(-) diff --git a/config.h b/config.h index 8a3e1c9..45cec00 100644 --- a/config.h +++ b/config.h @@ -1,5 +1,8 @@ #define DEFAULT_GRAMMAR "Cvccvc!##" +/* Use some static buffers to avoid malloc */ +#define STATIC_BUFFER_SIZE 24 + /* * For vowels: * i, o excluded due to potentially confusing 1/l/i + 0/o diff --git a/passgen.c b/passgen.c index 0b5f754..03f2ab9 100644 --- a/passgen.c +++ b/passgen.c @@ -86,18 +86,24 @@ unsigned int get_rng(void) return r; } +char grammar_buf[STATIC_BUFFER_SIZE + 1] = DEFAULT_GRAMMAR; +char password_buf[STATIC_BUFFER_SIZE + 1]; + char *build_grammar(int triplets, int specials, int numbers, int *grammar_size) { if (triplets < 1) { fprintf(stderr, "ERROR: Cannot have less than one triplet."); return NULL; } - *grammar_size = triplets * 3 + specials + numbers; - char *build = malloc(*grammar_size + 1); - if (build == NULL) { - perror("malloc"); - return NULL; + + char *build = grammar_buf; + if (*grammar_size > STATIC_BUFFER_SIZE) { + build = malloc(*grammar_size + 1); + if (build == NULL) { + perror("malloc"); + return NULL; + } } build[*grammar_size] = 0; @@ -113,10 +119,9 @@ char *build_grammar(int triplets, int specials, int numbers, int *grammar_size) int main(int argc, char *argv[]) { bool err = false; - bool custom_grammar = false; - char *grammar = DEFAULT_GRAMMAR; + char *grammar = grammar_buf; int grammar_size = sizeof(DEFAULT_GRAMMAR) - 1; - char *password = NULL; + char *password = password_buf; if (argc == 2) { /* Take first argument as the grammar */ @@ -132,14 +137,15 @@ int main(int argc, char *argv[]) err = true; goto cleanup; } - custom_grammar = true; } - password = malloc(grammar_size + 1); - if (password == NULL) { - perror("malloc"); - err = true; - goto cleanup; + if (grammar_size > STATIC_BUFFER_SIZE) { + password = malloc(grammar_size + 1); + if (password == NULL) { + perror("malloc"); + err = true; + goto cleanup; + } } password[grammar_size] = 0; @@ -179,9 +185,9 @@ cleanup: #ifdef USE_WINCRYPT CryptReleaseContext(win_rng, 0); #endif - if (custom_grammar) + if (grammar != grammar_buf) free(grammar); - if (password) + if (password != password_buf) free(password); if (err) -- cgit