I'm trying to write this simple code which takes the user input message, saves it on the stack, and then shows it back to the user.
I don't want to limit the number of characters the user can type in, so I used dynamic memory allocation each time the user enters a new character.
The code runs well if the user entered a small no. of characters, but it doesn't work if the user typed in a big no. of characters
for example: if I entered "Ahmed" it will show it back to me, but if I typed something with more characters it doesn't.
this is my code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *UserInput;
UserInput=(char *)calloc(1,sizeof(char));
int i=0,ii=0;
printf("Enter a message! \n");
while(*(UserInput+ii)!='\n'){
scanf("%c",(UserInput+i));
ii=i;
i++;
UserInput=realloc(UserInput,i*sizeof(char));
}
for(i=0;i<=ii;i++){
printf("%c",*(UserInput+i));
}
return 0;
}
int i=0-->int i=1(Sinceirepresents the secured size)*UserInput='1';realloc. fix like this