/* * Filename: dyninput.c * Authors(s): Roland (Roland@example.com) * Description: Short description here * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ #include #include #include char* dyninput_str(int_least64_t maxsize) { char* str = malloc(3 * sizeof(char)); if (!str) { puts("\nError allocating memory!"); return NULL; } int_least64_t size = 3, i = 0; char c = 0; do { if (size == maxsize) { printf("Character limit of %lld reached!\n", maxsize); break; } c = (char)getchar(); if (i + 1 == size) { char* tmp = realloc(str, size + 1); if (!tmp) { puts("Error (re)allocating memory!"); return NULL; } str = tmp; size++; } str[i] = c; i++; } while (c && c != '\n'); if (str[i - 1] != '\n') str[i - 1] = '\n'; str[i] = '\0'; // Sanitise stdin while (c != '\n') c = (char)getchar(); return str; }