C++ Logo

std-proposals

Advanced search

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

From: Andrey Semashev <andrey.semashev_at_[hidden]>
Date: Fri, 25 Jul 2025 15:03:01 +0300
On 25 Jul 2025 14:17, Frederick Virchanza Gotham via Std-Proposals wrote:
> I'm writing some code at the moment, and the destructor looks like this:
>
> ~Governor(void) noexcept
> {
> try
> {
> delete this->p;
> }
> catch(...){}
>
> this->p = (void*)0xdeadbeef;
> }
>
> I've set the pointer to 0xdeadbeef because I want to make sure that
> there's nowhere else in the code that this particular object gets
> deleted. If another part of the code goes to delete the object a
> second time, it will segfault on 0xdeadbeef -- which is exactly what I
> want to happen because I want the debugger to catch it.

And what if 0xdeadbeef is a valid pointer?

Even if it's not, you're not guaranteed to get a crash either. You may
get a corrupted heap and continue running with garbage data in your
memory, and undefined outcome.

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.

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;
  }

Received on 2025-07-25 12:03:06