2

I wrote a C program , and I am confused about the output of the program. The program is like this:

int main()
{
    char arr1[13] = "abcdefg";
    char arr2[10];
    gets(arr2);
    puts(arr2);
    strncat(arr1, arr2, 5); 
    puts(arr1);
    puts(arr2);

    return 0;
}

I input "qwertyuiop", and the result is :

qwertyuiop
qwert
qwertyuiopqwert

Can someone tell me why the value of arr1 turned into "qwert"? Many thanks!

huashui
  • 1,758
  • 2
  • 16
  • 24
  • possible duplicate of [How can gets() exceed memory allocated by malloc()?](http://stackoverflow.com/questions/20094586/how-can-gets-exceed-memory-allocated-by-malloc) – anatolyg Aug 28 '14 at 06:35

3 Answers3

2

Don't use gets to read the data from the user, If you enter the input more then the array size arr2[10], The array holds the 10 bytes, So there is no space for \0. It leads to "Undefined Behavior"

Due to this you are getting-

qwertyuiop
qwert
qwertyuiopqwert // Note the extra characters with arr2, That is more then your input

Use fgets to read input from user-

fgets(arr2,10,stdin);

Then the program is working fine. Try this change-

#include<stdio.h>
#include<string.h>
int main()
{
    char arr1[13] = "abcdefg";
    char arr2[10];
    // gets(arr2);
    fgets(arr2,10,stdin); // it will read only 9 characters from user, 1 byte for null
    puts(arr2);
    strncat(arr1, arr2, 5);
    puts(arr1);
    puts(arr2);

    return 0;
}

Output-

root@sathish1:~/My Docs/Programs# ./a.out 
qwertyuiopasdf   <- i have entered more than 10 character. But it reads only first 9 byte
qwertyuio
abcdefgqwert
qwertyuio
Sathish
  • 3,740
  • 1
  • 17
  • 28
2

The function gets reads in a string from stdin until it reads either a newline, or the end of file. In both cases it appends a NUL byte at the end.

Your input string qwertyuiop is 10 characters, so the total string length is 11 characters. You only allocated 10 characters in your array. So, the behaivour of your program is undefined. It could segfault, or behave weirdly.

In fact, the gets function is inherently dangerous. The man page says

Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead.

harmic
  • 28,606
  • 5
  • 67
  • 91
0

The value of arr1 is not "qwert"
I compiled and ran the program and it gives the following output

Output console:

[root@abhishek replies]# ./rep2   
qwertyuiop    
qwertyuiop   
abcdefgqwert   
qwertyuiop    
[root@abhishek replies]#

the program is working fine.
here strncat is working perfectly fine.

Abhishek Choubey
  • 883
  • 6
  • 16