4 ms·
I agree. In this case, writing memcpy by hand would work fine, but calling the standard memcpy is undefined. That's just silly. Undefined behavior should be
by marvy 12y ago
I agree. In this case, writing memcpy by hand would work fine, but calling the standard memcpy is undefined. That's just silly. Undefined behavior should be reserved for cases where making it defined is not easy.
- bodyfour 12y agoI would make a less-strict statement that "Undefined behavior should be reserved for cases where there might be some advantage for an implementation to do it a different way." For memcpy it's never safe for it to access the byte at "src+len" (it could be past the end of mapped memory) nor is it safe to write to "dest+len" So if len==0 it should follow that it won't access either src[0] or dest[0]. The spec basically allows len==0 to be a special case for this rule, although it's not clear what implementation would ever be able to take advantage of that.
- amaranth 12y agoEven better, your custom memcpy might sometimes result in working code and sometimes be replaced with a call to memcpy[1] and then break. When this happens will depend on the compiler and optimization level and even if you manage to write one that isn't replaced today the next version of GCC might be smart enough to figure it out. [1] https://gcc.gnu.org/bugzilla/show_bug.cgi?id=56888 https://gcc.gnu.org/bugzilla/show_bug.cgi?id=56888
- comex 12y agoOptimizing to assembly that calls the actual external memcpy implementation should be fine. If the custom memcpy works with NULL, without triggering undefined behavior, then any further optimization which assumes memcpy's NULL semantics would be clearly incorrect (which is not to say some compiler won't do it, but it would be a bug). The bug report you linked is about naming a function "memcpy", which is different - and IMO GCC's behavior was indeed incorrect until the change to disable the problematic functionality with -ffreestanding.