0

Try the below codes

Program1

#include<stdio.h>
int main()
{
    int i=2;  //two times
    while(i>0)
    {
        char ch[2];  
        scanf("%s",ch);   
        printf("%s\n",ch);
        i--;
     }
    return 0;
}

output (loop never terminate and take and print any length of string)

wdefgfvcdswdfetgyhujik
wdefgfvcdswdfetgyhujik
nbvewsq
nbvewsq
hgbvfdw
hgbvfdw
hbgfvedw
hbgfvedw
gfvdcwsq
gfvdcwsq
.
.
.

output(loop terminates when it take the valid set of string)

a
a
b
b

program2

#include<stdio.h>
int main()
{
    char ch[2]; 
    scanf("%s",ch);   
    printf("%s\n",ch);

    return 0;
}

output(How does it print and say Segmentation fault)

sxdfvghujiuytredwsazxacdfv
sxdfvghujiuytredwsazxacdfv
Segmentation fault

Sathvik
  • 565
  • 1
  • 7
  • 17
  • 4
    `char ch[2];` can't hold a string like `sxdfvghujiuytredwsazxacdfv` (in fact, it can hold only only one character and the null terminator). Entering those big strings is undefined behavior, and segmentation faults are a common manifestation of UB. – Blaze Oct 16 '19 at 11:27
  • 2
    Possible duplicate of [How to prevent scanf causing a buffer overflow in C?](https://stackoverflow.com/questions/1621394/how-to-prevent-scanf-causing-a-buffer-overflow-in-c) – Karl Knechtel Oct 16 '19 at 11:29
  • Strings in C are null terminated and that's that. – Lundin Oct 16 '19 at 11:32
  • @Blaze try this code https://onlinegdb.com/SymqyYEYB see line 17 event though the buf size is 4 it is working – Sathvik Oct 16 '19 at 11:32
  • @Blaze that's a wonderful example. Thanks :) – Sathvik Oct 16 '19 at 11:48

1 Answers1

3

Regarding the first problem:

If you will debug the program you can easily see that the endless loop is cause because you overwrite the i not using the scanf properly, the fix for the second problem should fix that to.

Regarding the second problem:

You are using the scanf function, which isn't safe due to the fact that it reads the entire input from user regardless of the size of buffer you allocated (in your case char ch[2].

so although it does enters the entire string sxdfvghujiuytredwsazxacdfv to the ch it is obviously overflowing -> thus segmentation fault is inevitable. Instead use scanf_s and restrict the amount of characters to read.

Note:

If youll raise warning flags it should appear that scanf is problematic and unsafe

David
  • 8,113
  • 2
  • 17
  • 36