implement handling of maxsize param

This commit is contained in:
Roland W-H 2022-11-19 16:50:53 +00:00
parent 236dbce306
commit 1fde10d2f5
1 changed files with 33 additions and 26 deletions

View File

@ -15,37 +15,44 @@
char* dyninput_str(int_least64_t maxsize) char* dyninput_str(int_least64_t maxsize)
{ {
char* str = malloc(3 * sizeof(char)); char* str = malloc(3 * sizeof(char));
if (!str) if (!str)
{ {
puts("\nError allocating memory!"); puts("\nError allocating memory!");
return NULL; return NULL;
} }
int_least64_t size = 3, i = 0; int_least64_t size = 3, i = 0;
char c = 0; char c = 0;
do
{
if (size == maxsize)
{
printf("Character limit of %lld reached!\n", maxsize);
break;
}
do
{
c = getchar();
if (i + 2 == size)
c = (char)getchar(); c = (char)getchar();
if (i + 1 == size) if (i + 1 == size)
{ {
char* tmp = realloc(str, size + 1); char* tmp = realloc(str, size + 1);
if (!tmp) if (!tmp)
{ {
puts("Error (re)allocating memory!"); puts("Error (re)allocating memory!");
return NULL; return NULL;
} }
str = tmp; str = tmp;
size++; size++;
} }
str[i] = c; str[i] = c;
i++; i++;
} while (c && c != '\n'); } while (c && c != '\n');
str[i] = '\0'; if (str[i - 1] != '\n') str[i - 1] = '\n';
str[i] = '\0';
return str; // Sanitise stdin
while (c != '\n') c = (char)getchar();
return str;
} }