1
int main(){
    char s[]="hi ";    
    char t[55];
    fgets(t,55,stdin); 
    strcat(s,t);
    puts(s);
}

I want to concatenate the strings s and the entered string t, but I'm not getting any output. I have tried using gets to read the string but the compiler says "use of gets can be dangerous". What should I do?

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
D...
  • 57
  • 8

4 Answers4

3

strcat(s,t); is overrunning the destination memory buffer s, as it is only large enough for 4 characters (and one of those is occupied by the NUL-terminator).

The behaviour of your program is therefore undefined.

Make the size of s large enough to accommodate its initial contents plus the largest string possible in t.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • But even if i try printf(" %s%s ",s,t); instead of concating . the output will print only s part i.e. hi – D... Jan 24 '17 at 08:37
  • But even if i use 'printf("%s %s",s,t);' instead of concating. Program gives output of s alone . – D... Jan 24 '17 at 08:44
  • @bhartendupandya can't reproduce, here it works fine. Maybe you should post another question for this issue.`int main() { char s[] = "hi "; char t[55]; fgets(t, 55, stdin); printf(" %s%s ", s, t); }` works fine here. – Jabberwocky Jan 24 '17 at 09:23
3

The array s doesn't have enough space to append t to it. You need to increase its size sufficiently.

char s[]="hi ";  

is an array of 4 characters. It can't hold more any more bytes that you'd want to append. Thus the your code has undefined behaviour.

If you increase the array size, for example, to 100:

char s[100]="hi ";  

Now, you'd be able to append further 96 bytes to it.

In cases in C, you always have to think of overrunning buffers.

NB: You should also check if fgets() succeeded before attempting to append t. In case, fgets() failed, the contents of t is indeterminate.

Community
  • 1
  • 1
P.P
  • 117,907
  • 20
  • 175
  • 238
3

The character array s should have enough memory to accommodate the string read in the array t. Thus it should be declared at least like

char t[55];
char s[sizeof( t ) + 3] = "hi ";

Also the function fgets can append the string by the new line character. In general you should remove it. This can be done the following way

t[strcspn( t, "\n" )] = '\0';

Take into account that according to the C standard function main without parameters should be declared like

int main( void )

The program must contain headers

#include <stdio.h>
#include <string.h>
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
-1

here was the same question asked

Why is the gets function so dangerous that it should not be used?

use fgets instead

Community
  • 1
  • 1
Matthias
  • 86
  • 5