0

I have declared a character array of size 4. When I take a string input even of size 5, the program prints the correct string. Why does this happen? With 8 characters too, it prints the right string but with 9 characters it gives an error.

#include <iostream>
using namespace std;
int main()
{
    char s[4];
    scanf("%s",s);
    printf("%s",s);
}

Error when I try to take input as a 9 character long string:

abcdefghi
*** stack smashing detected ***: /home/shivam/Study/standardproblems/stacks/temp terminated
abcdefghiAborted (core dumped)
Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
Shivam Mitra
  • 1,040
  • 3
  • 17
  • 33
  • 1
    Undefined behavior means that *anything* can happen. – Bo Persson May 30 '16 at 20:54
  • @BoPersson No, it means anything can happen as far as the ISO C standard is concerned. – Kaz May 30 '16 at 21:02
  • @Kaz - If you write to a random memory location, that might reprogram your display card, format your hard drive, or - if you work [at the Pentagon](http://time.com/4348494/pentagon-nuclear-floppy-disks/) - initiate a nuclear launch sequence. – Bo Persson May 31 '16 at 06:44
  • @BoPersson Rather, none of those actions would not be classified as ISO C as nonconforming. Undefined behavior is a very broad category, which encompasses useful implementation extensions. When you use `__builtin_expect` in GCC, that is also undefined behavior; yet it will not initiate a nuclear launch sequence. – Kaz May 31 '16 at 13:56

0 Answers0