-4

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"
genpfault
  • 51,148
  • 11
  • 85
  • 139
clown
  • 1
  • 1

1 Answers1

0

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);
}    
Jörg Beyer
  • 3,631
  • 21
  • 35