3 ms·
Something I'd consider strange and unexpected is that passing NULL pointers as destination to `memset` or `memcpy` is undefined behavior, even if the `size` arg
by nwellnhof 8y ago
Something I'd consider strange and unexpected is that passing NULL pointers as destination to `memset` or `memcpy` is undefined behavior, even if the `size` argument is zero. So compilers are allowed to remove null checks after calls to such functions and AFAIK already implement such optimizations:
memset(dest, value, size);
if (dest == NULL) {
// will be optimized away, although size could be 0.
}
I think most people would agree that `memset(NULL, v, 0)` should simply be a (well-defined) no-op and not result in undefined behavior.
- MaxBarraclough 8y agoEven without redefining those functions, it doesn't seem like too much to ask to have a runtime check and a noisy explosion, at least in debug builds.
- jstimpfle 8y agoThe problem is that array bounds are not available in general. If you use global static arrays compilers can indeed insert checks. In other cases the size might for example be bounded by a terminator sentinel, or have an implicit size based on other runtime variables, etc.
- MaxBarraclough 8y agoIndeed. To rework the whole ecosystem to enable bounds-checking would be quite a task. External native code that allocates, alloca... not easily done. Not as 'tidy' as Java/.Net where arrays are just somewhat special objects.