C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Standardising 0xdeadbeef for pointers

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Fri, 25 Jul 2025 13:19:41 +0100
On Fri, Jul 25, 2025 at 1:03 PM Andrey Semashev wrote:
>
> There is only one pointer value that is guaranteed to not point at any
> object, and that's nullptr. If you want to add another one, that would
> have to go beyond just defining a new constant. The whole runtime
> (including but not limited to the memory allocator) would have to be
> updated with support for this new constant.


Not really. There isn't a computer in existence today -- I don't think
-- that uses more than 49 bits for a memory address. 64-Bit ARM uses
48 bits but it can be extended by 1 bit to 49 bits.

So you can mark a pointer as 'bad' by manipulating the top 15 bits. Or
even just set the top bit high.


> You can also create "invalid" pointer values yourself, which are "safe"
> to a certain degree. For example:
>
> void* make_invalid_ptr()
> {
> // Mark it const so that it is hopefully placed in a read-only
> // memory region, which would prevent modifications by the
> // memory allocator. Also make it large enough so that the
> // allocator doesn't corrupt neighbouring data.
> static const unsigned char dummy[PAGE_SIZE] = {};
> return dummy + PAGE_SIZE / 2;
> }


Not a bad idea. So internally the compiler would do something like:

    constexpr unsigned PAGE_SIZE = 1024u;

    struct badptr_t {
        alignas(PAGE_SIZE) inline static char unsigned const
dummy[PAGE_SIZE] = {};

        template<typename T>
        operator T*(void) const
        {
            return static_cast<T*>( const_cast<void*>(
static_cast<void const*>( dummy + PAGE_SIZE / 2u ) ) );
        }
    };

    constexpr badptr_t badptr{};

    #include <iostream>

    int main(void)
    {
        char *p = badptr;
        std::cout << p << std::endl;
    }

Then whenever a pointer is dereferenced when NDEBUG is undefined, the
compiler checks if the pointer points inside badptr_t::dummy.

Received on 2025-07-25 12:19:54