#include <stdio.h>
#include <stdlib.h>
void input_all(char* array)
{
int c = 0;
int increse = 20;
int number_of_char = 0;
for (int increment = 0; (c = getchar()) != '\n'; increment++)
{
++number_of_char;
if (number_of_char % 10)
{
array = (char*)realloc(array, increse + sizeof(char));
if (array == NULL)
{
printf("not alocated!");
exit(22);
}
increse += 10;
}
array[increment] = c;
}
printf("%s\n", array);
}
int main(void)
{
char* array = (char*)malloc(10);
if (array == NULL)
{
printf("not alocated\n");
exit(33);
}
input_all(array);
printf("%s\n", array);
return 0;
}
So what I'am trying to do is to fill up "array" with getchar. When I try to print it out I get some garbage values at the end (most of the time). I think the problem is that I'am giving out to much space to "array" with realloc but I have no idea how to fix it. I also tried placing all the sizes to 1 in malloc and realloc and increse so that whenever i get a charcter the size of "array" increses but it still did not work. Anyone have any idea how ot fix it? Thanks in advance!
for(int increment = 0; (c = getchar()) != '\n'; increment++)will become an infinite loop if your input stream is closed without ever providing a newline. You must also check for EOF.return array;