1

Consider following program.

#include <stdio.h>
int main(void)
{
    char side_a[] = "Side A";
    char dont[] = {'W', 'O', 'W', '!' }; 
    char side_b[] = "Side B";
    puts(dont); /* dont is not a string */
    return 0;
}

I know that puts() function stops when it encounters the null character. But in above program I haven't specified null character. So when it stops printing? Is this program invokes undefined behavior? Is it guaranteed to get same output for this program on various C compilers? What the C standard says about this?

Destructor
  • 14,123
  • 11
  • 61
  • 126
  • In C a valid string is the one which is null terminated , all lib API's expect the null terminated string – Gopi Jun 06 '15 at 09:58

3 Answers3

4

puts will end up reading past the last element of dont, which is undefined behavior.

So no, you are not guaranteed the same output every time. You're not guaranteed any output at all for that matter - you're not guaranteed anything since this is undefined behavior.

Mat
  • 202,337
  • 40
  • 393
  • 406
3

Yes, this error results in your program having no defined behavior. As the term indicates, you can't expect anything reasonable to come out of the execution of such a program.

Jens Gustedt
  • 76,821
  • 6
  • 102
  • 177
2

Yeah it will be Undefined Behaviour, so output won't be same all the time. If you want to print in such case, I would suggest as below to have uniform output:

printf("%.*s", 4, dont);
Amol Saindane
  • 1,568
  • 10
  • 19
  • 1
    Good suggestion. One would be tempted to use `sizeof(dont)` to handle changes in its definition gracefully, but be careful to cast it as `(int)` to avoid undefined behaviour: `printf("%.*s", (int)sizeof(dont), dont);`. This solution isn't perfect anyway since it would silently misbehave if `dont` is changed to a `char *`. – chqrlie Jun 06 '15 at 09:55