Hacker News new | past | comments | ask | show | jobs | submit login

Ugh.. I'm generally in favor of the recent compiler optimizations dealing with assuming undefined behavior isn't triggered (although it has broken a lot of code that had made poor attempts at overflow checking, mine included) I think doing it for the mem* functions is a step too far.

I think it really was a defect in the C standard to not specify behavior of calls like memcpy(NULL, NULL, 0) It has obvious no-op semantics, and every implementation I've ever seen would accept it just fine. I bet there is a lot of code out there that assumes that memcpy() and friends work in this "traditional" way.




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.


I 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.


Even 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


Optimizing 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.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: