Malcolm said:
No. In general it works, which creates a huge problem with "portable enough"
programs which appear to work fine on most hardware, but might give wrong
results many years later when the original programmers have moved on and no
one can maintain the code.
Some time ago I wrote this function to fill a region of
memory with copies of a block of arbitrary size:
#include <string.h>
void
fillmem(void *pdest, size_t sdest, const void *pfrom, size_t sfrom)
/*
* Fills the `sdest' bytes starting at `pdest' with copies of the
* `sfrom' bytes starting at `pfrom'. The final copy will be partial
* if `sfrom' does not divide `sdest'.
*/
{
if (sdest > sfrom) {
/* Put one copy of the source pattern at the start of
* the destination.
*/
memcpy (pdest, pfrom, sfrom);
pfrom = pdest;
pdest = (char*)pdest + sfrom;
sdest -= sfrom;
/* Copy data from the beginning of the destination to
* the end, each iteration doubling the amount copied.
*/
while (sdest > sfrom) {
memcpy (pdest, pfrom, sfrom);
pdest = (char*)pdest + sfrom;
sdest -= sfrom;
sfrom += sfrom;
}
}
/* Fill the final (or only) piece of the destination.
*/
memcpy (pdest, pfrom, sdest);
}
This could be used as a portable way to initialize an
array of `double's to zero -- or to 1.0, or to alternating
+42.0 and -42.0, or whatever.
<off-topic>
At first glance this function looks like it might be a
cache-killer, as those successively-doubling memcpy() calls
keep flooding the same set of cache lines. On the three or
four machines where I've tested it, though, I haven't seen
evidence of cache thrashing. Perhaps those systems' memcpy()
implementations use special memory-to-memory data paths that
avoid flooding the cache -- I don't really know, and haven't
cared enough to study it closely. If anyone wants to research
this at greater depth -- or even just report that it does or
doesn't kill the cache on System X -- I wouldn't mind hearing
about your experiences.
</off-topic>