0

In the program below, if I enter "sbsbsbsbssbsbsbsbsbsbsbsbsbsbs" or even more characters, this program works and prints the value. Can someone please explain why?

int main()
{
 char *s = strdup("");
 scanf("%s",s);

 printf("\nInput:\t%s\n",s);
 return 0;
}

Thanks

psingh
  • 47
  • 1
  • 4
  • 2
    Because it hasn't broken anything (yet). I threw a tomato at the window. Why didn't it break? – Weather Vane May 12 '20 at 10:54
  • 1
    Essentially: https://stackoverflow.com/questions/1239938/accessing-an-array-out-of-bounds-gives-no-error-why – Mat May 12 '20 at 10:54
  • 2
    It's because of something called _undefined behavior_. – Ted Lyngmo May 12 '20 at 10:54
  • Side note: `free(s);` after the scanf is I think likely to break if you've written enough data in there. – Mat May 12 '20 at 10:56
  • 6
    there is no rule that says: When you cross a red light you will be hit by a car. There is a rule that says: Do not cross red lights. Similar here, speciftying what happens when you compile and and run wrong code would be rather pointless, because we care about correct code that has well defined behavior. Yours has undefined behavior – 463035818_is_not_an_ai May 12 '20 at 10:57
  • Thanks, everyone for the comments – psingh May 12 '20 at 11:01

0 Answers0