[Bug c++/71885] Incorrect code generated with -01, memset() function call is missing
eric at baculasystems dot com
gcc-bugzilla@gcc.gnu.org
Fri Jul 15 05:40:00 GMT 2016
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=71885
--- Comment #4 from Eric Bollengier <eric at baculasystems dot com> ---
I don't know exactly when someone decided that a doing memset(buf, 0,
sizeof(buf)); leads to an "undefined behavior", but it's how C and C++ work
since quite long time. And it's also why the operator new() is so useful.
I see the interest of the optimization, however I think that it's not correctly
implemented.
If GCC can find out that the code is
void *operator new(size_t x) {
...
a = malloc(x);
memset(a, 0, x);
return a;
}
Then, it is probably OK to strip out the memset() call. However, here, the
optimization looks to be only about the memset followed by the return call in
the new operator.
void *operator new(size_t x) {
memset(a, 0, x);
return a;
}
GCC doesn't check that the memory is coming from a malloc() call or if
something was modified in the memory before striping out the memset
automatically. I think that it is an incorrect behavior. The memory can come
from various places (like a pool of existing buffers), it can be dirty due to
some work done before the memset.
It looks that the optimizer thinks that the object returned by the function is
a "dead object", but it is not the case, we return it to the caller.
The written code explicitly asks to set a value to a memory area (to avoid
undefined behavior), and the compiler decided to not do what is written, and it
leads to a situation where the memory doesn't contain what the program expects.
Thanks,
Best Regards,
Eric
More information about the Gcc-bugs
mailing list