Paul D. Smith said:
nm> I'm not sure.
I guess I wanted to point out that "all you have
nm> to do is ..." introduces a portability problem. And just for
nm> reliably allocating some piece of memory.
Well, malloc() can't be implemented in portable C anyway of course.
We're not talking about implementing malloc in portable C - it's part of the
standard library. It's reasonable to assume that the standard library will
be implemented to integrate (efficiently) with the execution environment
which will almost certainly mean an environment-specific implementation. The
concern is that library implementations are not implementing the required
semantics (although I also accept that the C library implementations may in
turn be being stymied by the environment to some extent).
Yes, if you wanted to write a 100% portable, 100% foolproof wrapper for
malloc() you wouldn't be able to make use of this capability. You can
write a reliable POSIX-portable version, though, and/or you can make a
very conservative assumption and write every 256th byte and call it good.
"Reliable on POSIX only", "very conservative". Neither of these equates to
"portable" as far as I'm concerned.
What other standard library routines would you not mind getting lies back
from? Douglas A Gwyn mentioned the file access functions in another
article. What if fopen() returned a valid non-NULL handle but then just
caused a crash when you tried to read data from it. In fact, it is quite
possible that this behaviour can occur if the C library's stdio buffering is
using malloc to allocate the buffer memory. You open the file, get a valid
handle, you're not at the end of the file, the file is buffered, you call
getc() and a crash occurs (in __filbuf or whatever the buffer filling
routine is called) because the buffer was "successfully" allocated yet the
memory wasn't actually available. If it had been told that memory wasn't
available in the first place, __filbuf (or whatever) could have disabled
buffering on the FILE stream or the fopen() could have been failed in the
first place or something.
Heck, even if you are ridiculously conservative and write every 5th byte
that's still only 20% of the effort it would take to write all of them
To be honest, the chances are that memset would be more efficient than that
on many systems (although devious implementations could end up doing
something sneaky with page mapping and copy-on-write that defeats it). But
we're talking about having to take silly, timewasting and
implementation-specific measures just to ensure that the library is
implementing the required semantics.