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?
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?
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.
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.
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;
.
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.
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?
Commented
Jun 20, 2013 at 8:49
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)
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
.
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
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.