User input function C
Hi all! I've got a problem with reading user input from a console. I am trying to implement function that reads and allocates memory from the console in chunks.
First issue
First issue is I am getting some artifacts at the beginning of the output. For an input:
Sample input 1
Sample input 2
Sample input 3
Sample input 123
I get:
_←Sample input 1
_♂Sample input 2
_|Sample input 3
_ľSample input 123
In debugger char buffer[block_size];
variable looks fine, after fgets(buffer, block_size, stdin) != NULL
is executed.
and I think that problem occurs in strcat(input, buffer);
. I have no idea why it does that. My guess I am allocating/reallocating memory wrong.
Second issue
Second issue is that console outputs maximum of 4091 characters on Windows, with artifacts at the beginning. I have tried inputs like 5000 or 8000 'a' characters.
Is it possible to increase the input without overcomplicating my code?
Additional information
I'm using Windows 10 Pro, Version: 10.0.19044 Build 19044.
Clion IDE.
MinGW toolset.
C11 standard.
On Linux Mint machine I do not get artifacts and the console output is 4096 characters.
I do not get any errors.
Code
#include <stdio.h>
#include <malloc.h>
#include <string.h>
char *user_input();
int main() {
char *x = user_input();
printf("%s", x);
return 0;
}
char *user_input() {
const int block_size = 200;
size_t temp_str_size, general_str_size = 0;
char buffer[block_size];
//allocates memory
char *input = malloc(block_size * sizeof(char));
do {
//reads input to buffer
if (fgets(buffer, block_size, stdin) != NULL) {
temp_str_size = strlen(buffer);
//reallocates whatever memory is needed for input
realloc(input, temp_str_size general_str_size);
//null check
if (input == NULL) {
printf("Unable to reallocate memory\n");
return NULL;
}
strcat(input, buffer); // probably problem occurs here
// increases general string size for expanding memory reallocation
general_str_size = temp_str_size;
} else {
return NULL;
}
} while (temp_str_size == block_size - 1);
return input;
}
CodePudding user response:
strcat(input, buffer)
both params need to contain strings. input
content is unintialised and hence has indeterminate values. Initialise with input[0] = '\0'
after malloc
.