-3
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char* str;
int i;
printf("Enter the String:\n");
gets(str);
int len=strlen(str)-1;
while(len>0&& isspace(str[len]))
len--;
str[len+1]='\0';
printf("Output string:\n%s\n",str);
return 0;
}

this code works absolutely fine when input is small like" trail space" but crashes on large inputs like" trailing space deleted". I dnt know whay this is happening so please help me. this program removes trailing spaces at the end of string.

  • 1
    [You should not be using `gets()`](http://stackoverflow.com/questions/1694036/why-is-the-gets-function-is-dangerous-why-should-not-be-used). – nickb Jan 26 '13 at 23:23
  • when u write like this `char* str;` you have a pointer that points somewhere so when you use that in `gets()` the characters are written somewhere in memory where `str` happens to be pointing. – AndersK Jan 26 '13 at 23:43

1 Answers1

1

because str is never initialized and is pointing to junk data.

You're lucky and this is Undefined behavior

Instead use malloc() to dynamically allocate memory for str and it'll do I guess.

Like this: char *str = malloc(100); // say for 100 characters

len will then be less than or equal to 100 (and should include '\0')

Also note, using gets() is a bad idea. instead use fgets() or gets_s() function

Aniket Inge
  • 25,375
  • 5
  • 50
  • 78
  • this dosent work. this malloc assignent gives a void* to char* error. try it on your compiler. I have tried it on both netbeans and devcpp . – Mragank Yadav Feb 04 '13 at 06:34