T
Tim Rentsch
That's the undefined part. OP went outside the spec and got
lucky. That won't always happen.
I'd like to offer some counterpoint to the various "what
happened is undefined behavior" remarks.
1. There may indeed have been a declaration in scope,
resulting from flags or compiler option settings. We
cannot say for sure just by looking at the source.
2. Presumably the code compiled and ran, so either
there was an earlier declaration, or one was not
necessary for a successful compile.
3. A declaration is not necessary for a successful
compile in C90. Alternatively, there may have been a
compiler option to treat an undeclared function the
same way as C90 does (after issuing a diagnostic) in a
C99 compilation, which is a conforming choice.
4. Under C90 rules, there is technically undefined
behavior because of type incompatibility, but of a kind
that is benign in implementations where (as is likely
here) size_t == unsigned int (and ssize_t == int).
That's because of guarantees about representations of
the types involved, and also because of what happened
later with C99 (see next).
5. Under C99/C11 rules, the situation mentioned in (4)
was incorporated into the language definition and is
defined behavior.
6. The ISO C standard and POSIX both use (AFAIK) the
term "undefined behavior", and it may even be defined
the same way in both cases. In spite of that there is
a big difference between the two kinds of undefined
behavior, and glossing over that distinction does more
harm than good.
7. AFAICS there is no undefined behavior as far as the
write() call itself is concerned. Looking at the man
page, what write() does looks well-defined for all inputs
(with some non-portable aspects for special files, but
still not undefined behavior). What this write() call
does may be surprising and unexplained by its defining
document, but that's not because of undefined behavior
in the write() call.
8. The question being asked orginally is about why a call
to write() on stdin works. The answer to that question
has to do with the environment where the program was run,
even in the case where size_t != unsigned int. Focusing
on undefined behavior, especially to the exclusion of
other considerations, is a distraction from the question
and a disservice to the questioner.
9. Some people may feel that the posted code displays
some poor coding practices (or fails to follow some good
ones), and consider it important that these be pointed
out. And maybe that's right. But just saying the code
has undefined behavior is not a good way to do that.