Reputation: 14438
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?
Upvotes: 1
Views: 869
Reputation: 1598
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);
Upvotes: 2
Reputation: 78923
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.
Upvotes: 3
Reputation: 206699
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.
Upvotes: 4