Am 15.03.2014 00:57, schrieb David Laight: > They are only 'safe' in that you pass the length of the target buffer. > There are still plenty of ways things can go wrong. > To make them 'safe' would need 'fat pointers' and run time checks > (possibly done by the hardware) to ensure that the code didn't > write beyond the memory that was supposed to be accessible from the > pointer.
The solution shows up when looking beyond one's own nose. Again, if all one knows and is ready to accept is C89 or possibly C99 (which lacks commercial compiler support), and one waives using or writing string libraries, then one loses, and due to a deliberate choice. Such "fat pointers" with automated reallocation have been in, for instance, C++'s standard library for many years now (#include <string>, std::string type). I'm sure C#, Java and other languages have similar concepts. My point being is that plain C serves different purposes. If you take it outside systems programming to applications programming, there are sure to be pains. It works, for one because it's Turing complete, but as you state, it is cumbersome to get robust and right. >>> Some system's header files have started forcing programs to check >>> the error returns from some library functions. >>> That gets to be a PITA - in some cases you really don't care. >> >> Cast to void. > > Nope - that isn't enough. > I got away with 'if (foo(...));' - but I'm sure it won't last. Then switch the warning off and file a bug report against the compiler. >>> Also any program that looks at the return value from fprintf() >>> is probably broken anyway! >> >> Why? Buffering doesn't make error checking useless. > > True, but any error is most likely to happen during the fflush() > that happens during fclose(); Or in the midst when the stdio buffer is flushed. Or sooner, depending on setvbuf()/setbuf() calls. (_IONBF, _IOLBF). > So if you care about errors do "fflush(); err = ferror(); fclose();" > Or call ferror() at at appropriate point in a program loop to > terminate early. Checking every fprintf() just makes the code unreadable. Until the time when you start debugging multi-character charset issues and want to see the EILSEQ as early as possible. Again, C was not designed for application programming.
