0
#include<stdio.h>
int main(){
    char w[3];
    scanf("%s",w);
    printf("%s\n",w);
    return 0;
}

For example, if I give a string 'Goods' which has 5 characters. But my array will accommodate only 2 characters and a \0. I got output as 'Goods' why?

sonicbuzz
  • 5
  • 2
  • 1
    You invoke *Undefined Behavior* writing beyond the end of your array. You cannot use `scanf()` to read into an array without also using the *field-width* modifier to protect your array bounds, e.g. `scanf ("%2s", w)` -- otherwise using `"%s"` is no safer than `gets()`. See [Why gets() is so dangerous it should never be used!](https://stackoverflow.com/q/1694036/3422102) – David C. Rankin Jun 02 '21 at 16:34
  • 1
    You'll write past the bounds of the array. It's undefined behavior. Possible outcomes are a segmentation fault, variables mysteriously changing their values, or in some cases you might not notice anything. Just don't do it. – Tom Karzes Jun 02 '21 at 16:34
  • 2
    *"my array will accommodate only 4"* - your array will only accomodate **2**, plus the `\0` terminator which is automatically added by `scanf`. – Marco Bonelli Jun 02 '21 at 16:36
  • effectively a dupe of good ol' [Undefined, unspecified and implementation-defined behavior](https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior) – underscore_d Jun 02 '21 at 16:36
  • Always better to take user input with `fgets()`, e.g. `char w[3]; if (fgets (w, sizeof w, stdin)) puts (w);` That limits you to reading no more than `2` characters plus the nul-terminating character into `w`. Also, *Don't Skimp on Buffer Size!*. Better to have 10,000 characters too many than 1 character too few. Literally hundreds of answers on this site about how to correctly handle user-input. – David C. Rankin Jun 02 '21 at 16:41

1 Answers1

1

You will have input overflow the buffer you pass. This will invoke undefined behavior. This behavior could be nothing on the moment or crash the application much later. You could have segment violation and more adverse effects.

To avoid that, you should use fgets() to read a string and then sscanf() to parse it. fgets() takes the size of the buffer as argument and prevent the buffer overflow.

fpiette
  • 11,983
  • 1
  • 24
  • 46
  • Or use the correct specifier in `scanf` to limit the number of characters allowed for the size of the char array: `%2s` – isrnick Jun 02 '21 at 17:36