I am writing a program which takes in user input character by character and print it out at the end:
#include <stdio.h>
#include <stdlib.h>
#define FACTOR 2
int main(void) {
printf("Enter line: ");
int curr_size = 10;
char curr_char = 0;
char *ptr = malloc(curr_size * sizeof(char));
int num_of_chars = 0;
while (1) {
int res = scanf(" %c", &curr_char);
if (res == EOF) {
break;
}
if (res != 1) {
printf("Error: %c is not a character", res);
break;
}
if (num_of_chars == curr_size) {
curr_size = FACTOR * curr_size;
ptr = realloc(ptr, curr_size);
}
ptr[num_of_chars] = curr_char;
num_of_chars++;
}
printf("%s\n", ptr);
return 0;
}
However, I notice that whenever I enter a line more than 10 characters (which trigger realloc), there is a unknown character appended at the end of my line when outputing:
If I change ptr[num_of_chars] = curr_char;
to *(ptr + num_of_chars) = curr_char;
the character disappear, may I know why and how to fix it? Thanks in advance.