On 2/13/21 7:31 PM, Martin Sebor wrote:
The test case in PR 99074 invokes dynamic_cast with the this pointer
in a non-static member function called on a null pointer. The call
is, of course, undefined and other different circumstances would be
diagnosed by -Wnonnull. Unfortunately, in the test case, the null
pointer is the result of inlining and constant propagation and so
detected neither by the front end -Wnonnull nor by the middle end.
The program ends up passing it to __dynamic_cast() which then
crashes at runtime (again, not surprising for undefined behavior.
However, the reporter says the code behaved gracefully (didn't crash)
when compiled with GCC 4.8, and in my tests it also doesn't crash
when compiled with Clang or ICC. I looked to see if it's possible
to do better and it seems it is.
The attached patch improves things by changing __dynamic_cast to
fail by returning null when the first argument is null, and also
This hunk is OK.
by declaring __dynamic_cast with attribute nonnull so that invalid
calls to it with a constant null pointer can be detected at compile
time.
This is not; dynamic_cast is specified to return null for a null operand.
"If v is a null pointer value, the result is a null pointer value."
The undefined behavior is the call to _to_object, not the dynamic_cast.
Since the test case is undefined it seems borderline whether this
can strictly be considered a regression, even if some previous
releases handled it more gracefully.
Indeed. But handling the null case in __dynamic_cast as well as in the
compiler seems harmless enough.
Jason