42

I'm learning C++ and reading C++ Primer. There's a question I would like to know the answer:

Given a pointer p, can you determine whether p points to a valid object? If so, how? If not, why not?

7
  • 1
    Please define "valid."
    – tckmn
    Commented Jun 19, 2013 at 22:41
  • 3
    Precisely what smart pointers are good for.
    – chris
    Commented Jun 19, 2013 at 22:46
  • if you know how the underlying memory manager works (how it does its book keeping), then you could perhaps figure it out. However, this would be very platform specific. If you manage memory by yourself, then that should not be a problem. The best course of action is still to stick to best practices (RAII, encapsulation).
    – didierc
    Commented Jun 19, 2013 at 23:48
  • @chris - sort of what smart pointers are good for. But GIGO still applies; you can always create smart pointer that holds a bad pointer. Commented Jun 20, 2013 at 11:18
  • 2
    Possible duplicate of Testing pointers for validity (C/C++)
    – jwodder
    Commented Jun 13, 2016 at 21:02

6 Answers 6

49

No, you can't. Why? Because it would be expensive to maintain meta data about what constitutes a valid pointer and what doesn't, and in C++ you don't pay for what you don't want.

And you don't want to check whether a pointer is valid, because you know where a pointer comes from, either because it's a private part of your code that you control, or because you specified it in your external-facing contracts.

4
  • I would argue that it really is not expensive... With the smart pointers that are now part of the standard library there is a very minimal amount of overhead. In the vast majority of use cases the benefit far outweighs the cost. See a related post for more info: stackoverflow.com/questions/22295665/…
    – tjwrona
    Commented Jul 25, 2019 at 15:28
  • @tjwrona1992: That seems overly simplistic and unrealistic. Smart pointers either have different semantics and hence aren't comparable (unique_ptr, shared_ptr), or they have the same semantics and also the same problems (observer_ptr). Note also that unique_ptr is in practice more expensive than a raw pointer when used as a return type due to poor ABI choices (it isn't returned in registers).
    – Kerrek SB
    Commented Jul 26, 2019 at 21:25
  • I'm not saying that they don't have a cost. All I'm saying is if you're not working in an embedded environment and writing code for a microprocessor with very limited memory and a slow clock speed the cost is essentially negligible compared to the benefits in nearly all use cases.
    – tjwrona
    Commented Jul 26, 2019 at 21:36
  • 1
    @tjwrona1992: Apart from the fact that there are real, big codebases that lament the unnecessary performance hit from unique_ptr (at a level where it incurs real dollar value cost), you've also ignored my main point: The smart pointers aren't a drop-in replacement, since they have different semantics. There's no obvious smart pointer, say, that you could realistically use for non-ownership-transferring reference semantics that would match the semantics of a raw pointer; that would require a different design.
    – Kerrek SB
    Commented Jul 26, 2019 at 22:05
16

Not possible. Think of this scenario.

int *ptr = new int(10);
int *ptrDup = ptr;

delete ptr;

But ptrDup still points to the memory location pointed by ptr which no longer exists. So, deferencing ptrDup results undefined behavior. But there is reference counting which is totally a different concept.

2
  • 10
    Actually, delete does not touch ptr itself, so ptr, too, still points to that same memory and dereferencing it also is UB...
    – Aconcagua
    Commented Jun 10, 2016 at 5:36
  • delete invalidates the pointer itself, too; if (ptr != nullptr) and if (ptrDup != nullptr) are both UB after the delete. They can be made valid again by reinitializing them after the delete by ptr = nullptr; ptrDup = nullptr;.
    – Eljay
    Commented May 13, 2022 at 16:12
10

Not really possible to see if a pointer is "valid" in all it's meanings.

Sure, you can try to dereference the pointer (*ptr = x; or x = *ptr). If your code didn't crash, the pointer is pointing to valid memory. If it crashed, obviously, the pointer is no good. Unfortunately, this approach is a bit like checking if a gun is loaded by firing it at your head - which isn't the cleverest... Unfortunately, with pointers, there is no "check the chamber to see if it's loaded", so no real good way to figure out if the a pointer is valid, other than "if it doesn't cause an hardware fault, it's valid".

Note that this will only really tell you that "the pointer is pointing at some memory you can access" in most cases. It does NOT mean that the pointer "is correct for what you want it to be" (e.g. it points to the correct type). And it CERTAINLY won't tell you if the pointer is pointing to "stale data" (that is, when a pointer WAS valid, but it's now memory used for something else).

Unfortunately, with 232 or 264 [actually 248] possibly valid memory addresses in a modern system, it's almost impossible to know what addresses are valid and which ones are not. Even inside the operating system, the way the OS figures out if it can write to the memory you asked it to write to is "try to write it, see what happens". For the OS, this works out fine, because it can be careful about "this may go wrong, and if it does, I'll continue over there in the error recovery code". The OS has to deal with this because it has to accept, a) that programmers make mistakes, and b) that some people actually write malicious code to TRY to break the OS.

The way for an application to "make sure pointers are valid" is that the programmer writes code that is CAREFUL about what it stores in pointers, how it frees those pointers, and only use pointers that have valid values stored in them. You shouldn't end up "having to check whether the pointer is valid" - then you are "doing it wrong".

(When you work with a system for a while, and reading pointer values in a debugger, you do after a while recognise "good" and "bad" pointers - but that's just because you learn what, usually, a good pointer vs. a bad pointer looks like. To write code to recognise such is almost impossible - especially if the system is allocating a lot of memory, so it uses most of the available space.)

Of course, in C++, there are smart pointers, vectors, and various other tools that mean a lot of the time you don't even have to bother with pointers. But understanding how to use pointers and how pointers work is still a good thing to do.

5
  • 1
    If you derefence a pointer-to-T that isn't pointing to an object of type T, behaviour is undefined - so your opening statement is false - it may not crash. Commented Jun 20, 2013 at 0:56
  • @user1131467: Ok, I have added a statement to that effect. My main point was really that "if you have a bad pointer (invalid, rather than pointing at wrong type), it's hard to find that out without crashing". Commented Jun 20, 2013 at 7:53
  • 2
    I'm not convinced that the first few paragraphs of this answer add anything useful to the post. Especially since the question is about whether a pointer points to a "valid object", not "valid memory". An invalid pointer is often a pointer which was valid until the user called delete, in which case it may "look" correct and seem to work but actually return zombie garbage which just happens to lie within the valid memory range of your application. So, with all these gotchas, maybe it's best to just leave it at "No" followed by how to avoid having to check validity of a raw pointer?
    – Agentlien
    Commented Jun 20, 2013 at 8:49
  • @Agentlien Ok, I've added a "first sentence" to say "No you can't". Commented Jun 20, 2013 at 8:58
  • That's actually enough of an improvement for my taste. +1
    – Agentlien
    Commented Jun 20, 2013 at 9:04
4

If a pointer is set to nullptr, that means it hasn't been given an object to point to and instead has been given a "default" value. It's possible that the pointer could not be assigned to nullptr and at the same time not be assigned to a valid object, but in that case it would be impossible to determine that. For example:

With nullptr:

int *ptr = nullptr;

// check if pointer is unassigned to an object
if (ptr == nullptr) ptr = new int{0};

Without nullptr:

int *ptr;

// using ptr while uninitialized is Undefined Behavior!
if (ptr != &some_object)
2

As stated in other answers, this is not possible with a raw pointer of the form SomeObject* somePointer. However, c++11 introduced a new set of dynamic memory management and new smart pointers. Using a smart pointer you can detect if the resource is still available. For example in the following:

std::weak_ptr<int> w; // Our pointer to a resource.
{
    std::shared_pointer<int> s = std::make_shared<int>(5); // The resource.

    w = s;       // We can set the weak pointer to the shared pointer.

    auto s2 = w; // Here we can promote the weak pointer to a shared  pointer to control 
                 // the resource.

    *s2 = 6;     // Here we can use the resource.

}                // Here the resource is destroyed.

auto s2 = w;     // Here we will fail to get the resource because it has been destroyed. We
                 // have successfully used smart pointers to detect if the resource exists.

Read more about std::shared_ptr and std::weak_ptr for more examples. Before c++11 equivelent types of smart pointers are available in boost.

2
  • Smart pointers are (much) better in C++11, but they were introduced long before...
    – Ben Voigt
    Commented Feb 7, 2018 at 0:22
  • 1
    @BenVoigt I will add the word new, but I don't really want to talk about auto_ptr here because i will need a page of why not to use it. I will add a note about boost as well. Commented Feb 7, 2018 at 0:48
-1

The C++ specification does not give us any kind of support to determine whether a pointer is valid. The best is to use smart pointers because you are much less likely to misuse them (they have various guards allowing proper manipulation).

However, various companies develop libraries and tools to add code to check each memory access and if one is invalid, you get an interrupt.

With g++, I use the sanitizer options like so:

g++ -fsanitize=address -fsanitize=enum -fsanitize=unreachable ...

The first one will protect your memory accesses to a point where trying to use the wrong pointer is going to be detected with a SEGV. It uses the MMU to protect your memory so it's hardware driven. It slows down your code, but it still pretty fast. One thing to watch out for in this mode, the binaries allocate 2Tb of virtual memory. You don't want to run too many such binaries simultaneously unless you have a lot of RAM.

As a side note: part of the code comes from Google and the first implementation was in clang.

In direct C/C++ under Linux, you can test whether a pointer is within your process. However, with large memory support, that will fail and you have to take the stack in account too. The start pointer is something like 0x400000. The end address of the heap can be determined using sbrk(). So your heap pointers should be between those two boundaries.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.