The logic here is wrong:
while((c = getchar()) != '\n') {
realloc(input, (sizeof(char)));
input[i++] = c;
}
You're not actually increasing the size of the buffer, and you are also discarding the result of realloc.
Try:
while ((c = getchar()) != '\n') {
// Note: you need one extra character for the terminator, so for the
// first char, when `i` is 0, then you need room for two `char`s in
// the buffer - one for the first input character and one for the
// terminator. And so on...
char * temp = realloc(input, i + 2); // NB: realloc can, and sometimes does, fail
if (temp == NULL) // if realloc failed then exit program
exit(1);
input = temp; // otherwise update input...
input[i++] = c;
}
Also, since you are always going to be calling realloc on every character (which is very inefficient, incidentally, but it works), this line:
input = (char *) malloc(sizeof(char));
(which should not have a cast, BTW, since this is C, not C++) can just be:
input = NULL;
And one final bug:
char c;
should be:
int c;
otherwise your while loop may never terminate, since EOF can only be properly represented as an int.
So the final fixed program should look something like this:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int i = 0;
int c;
char * input = NULL;
printf("Input a string, press ENTER when done: ");
while ((c = getchar()) != '\n') {
// Note: you need one extra character for the terminator, so for the
// first char, when `i` is 0, then you need room for two `char`s in
// the buffer - one for the first input character and one for the
// terminator. And so on...
char * temp = realloc(input, i + 2); // NB: realloc can, and sometimes does, fail
if (temp == NULL) // if realloc failed then exit program
exit(1);
input = temp; // otherwise update input...
input[i++] = c;
}
input[i] = '\0';
printf("\nYou've entered the string: %s\n", input);
return 0;
}