I was trying to make string type datatype in c with dynamic memory allocation.
my code is printing the characters which are inputted by the user but it is also printing some garbage value in next line. Why is this happening?
#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));
printf("Enter string : ");
while (a != '\n')
{
a = getchar();
str = realloc(str, sizeof(char) * (n));
str[i++] = a;
n++;
}
printf(str);
free(str);
}
input:
"q"
output:
q
"garbage value"