Swapnil Jain
Swapnil Jain

Reputation: 29

why is this C program not working correctly?

I tried to create my version of functions gets() and puts() for learning about them. The program which i wrote correctly displays the string but also some garbage characters.

Why does this happen?

/* xgets and xputs function */
/*Author : Swapnil Jain */
#include<stdio.h>
void xgets(char *);
void xputs(char *);
int main()
{
 char str[25];
 xgets(str);
 printf("\n");
 xputs(str);
 return 0;
}

void xgets(char *a)
{
 printf("Enter string\n");
 while(1)
 {
  scanf("%c",a);
  if(*a != '\n')
    a++;
  else 
    break;
 }
 a = '\0';
}

void xputs(char *a)
{
 while(1)
 {
  printf("%c",*a);
  if(*a != '\0')
    a++;
  else
    break;
 }
}

Input string:

Hello how are you

Output string:

Hello how are you
D�

Upvotes: 0

Views: 127

Answers (2)

rustyx
rustyx

Reputation: 85266

You're almost there. This seems like an attempt to null-terminate the input, only this particular expression at the end of xgets() has no effect

    a = '\0';

It sets the value of the a pointer itself to 0.

Just add a * in front of a to set the character pointed-to by a to 0:

    *a = '\0';

Note: Your code is susceptible to a buffer overflow because str has a fixed length of 25, which is not checked in xgets. You should pass the length of str as a second argument to xgets and check it there.

Upvotes: 5

Abhijit Pritam Dutta
Abhijit Pritam Dutta

Reputation: 5581

Better always initialized all the location of a char array with null character which is equivalent to 0 line below.

  char str[25];
  memset(str, 0, sizeof(str);

Also correct your code line below:-

 a = '\0';  to *a = '\0';

This will fix your problem.

Upvotes: 1

Related Questions