C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Calling methods on a nullptr

From: Magnus Fromreide <magfr_at_[hidden]>
Date: Sun, 27 Oct 2024 22:49:33 +0100
NO! NO! NO!

IBM's old xlC compilers allowed this (actually it allowed reads from
the NULL page) and the result was code littered with NULL checks on this
and bugs where one messed up and did null pointer dereferences or called
virtual methods on NULL, or even more fun, figured out that the member object
y, located at offset 16, should have a method call and then everything
breaks because 16 != NULL.

There is also the fact that this can't possibly work on current virtual
method implementations as it is unlikely that any readable virtual method
tables are located at NULL.

Please preserve everyones sanity and reject this!

/MF

On Sun, Oct 27, 2024 at 08:16:40PM +0000, Frederick Virchanza Gotham via Std-Proposals wrote:
> This is a totally half-baked idea, but I just want to float it here
> sort of like a thought experiment to see if anyone is intrigued by the
> possibilities it could open up.
>
> C++ could potentially allow the invocation of a method on a nullptr.
> For example:
>
> class MyClass {
> string name;
> public:
> string GetName(void)
> {
> if ( nullptr == this ) return {};
> return this->name;
> }
> };
>
> It gets a little more complicated if the method is virtual, for example:
>
> class MyClass {
> string name;
> public:
> virtual string GetName(void)
> {
> if ( nullptr == this ) return {};
> return this->name;
> }
> };
>
> Because if we supply the following standalone function to an x86_64
> compiler on Linux:
>
> string Monkey(MyClass *const p)
> {
> return p->GetName();
> }
>
> It will give us back something like:
>
> mov r11, rdi # Put the object pointer in R11
> mov r11, [r11] # Put the address of the VTable in R11
> mov r11, [r11] # Put the address of the first method in R11
> jmp r11
>
> This of course will segfault the first time it dereferences R11
> because it's a nullptr.
>
> But if we were to mark the class as nullptr-friendly:
>
> class MyClass friend nullptr {
> string name;
> public:
> virtual string GetName(void)
> {
> if ( nullptr == this ) return {};
> return this->name;
> }
> };
>
> Then our 'Monkey' function would then know to check first whether 'p'
> is a nullptr, and if it is a nullptr, then instead of dereferencing
> 'p' to find a VTable pointer, it instead just uses the VTable of
> MyClass.
>
> So it could be possible in the future in C++ to accommodate the
> invocation of a method on a nullptr.
> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals

Received on 2024-10-27 21:49:39