This is your program with minimal changes:
#include <stdio.h>
#include <stdlib.h>
void main(void)
{
int n = 1, i = 0;
char a = 0;
char *str = NULL;
str = malloc(sizeof(char) * (n+1)); // reserve space for a zero byte
printf("Enter string : ");
while (a != '\n')
{
a = getchar();
str = realloc(str, sizeof(char) * (n+1)); // reserve space for a zero byte
str[i++] = a;
str[i+1] = 0; // add a zero byte
n++;
}
puts(str); // puts instead of printf
free(str);
}
solved why code printing garbage value on screen with input string? [duplicate]