0

I was practicing in C gcc compiler for Strings and I got the below confusion between strlen and strcopy please tell me what kind of behavior it is? When I run my below Program without using Strlen function:

#include <stdio.h>
int main()
{
    int k;
    char p[5];
    char p1[10];

    printf("Enter String in p");
    gets(p);

    printf("String is %s\n",p);

    strcpy(p1,p);

    puts(p1);

    puts(p);

    return 0;
}

output:

Enter String in pshadab qureshi
String is shadab qureshi
shadab qureshi
eshi

and When I Run Program Using Strlen Function like:

#include <stdio.h>
int main()
{
    int k;
    char p[5];
    char p1[10];

    printf("Enter String in p");
    gets(p);

    printf("String is %s\n",p);

    k=strlen(p);

    strcpy(p1,p);

    puts(p1);

    puts(p);

    return 0;
}

Then the output is:

Enter String in pshadab qureshi
String is shadab qureshi
shada
shada

please explain me the behavior why is this happening?

  • 8
    Good illustration of why using `gets` is bad. – Eugene Sh. Jul 09 '20 at 15:18
  • 3
    You invoked *undefined behavior* by writing beyond the buffer. You shouldn't use `gets()`, which has unavoidable risk of buffer overrun, deprecated in C99 and removed from C11. – MikeCAT Jul 09 '20 at 15:18
  • 5
    [Never use `gets()`!](https://stackoverflow.com/q/1694036/10077) – Fred Larson Jul 09 '20 at 15:18
  • 3
    "pshadab qureshi" is longer than the 4 characters *p* can contains (minus 1 for null char), so *gets* writes after the array with an undefined behavior as already said – bruno Jul 09 '20 at 15:26
  • Then How Can I take space in string without gets or fgets @FredLarson – Sumit Agrawal Jul 09 '20 at 17:02
  • @SumitAgrawal: `fgets()` is fine, though your buffer is still smaller than the text you are entering. `gets()` is disaster. – Fred Larson Jul 09 '20 at 17:03

0 Answers0