1

I was given an integer pointer (passed through a function) which I can't modify that can possibly point to invalid memory or is a zero-pointer. I need to know if there's a way to check whether or not the pointer is pointing to invalid memory. Are there any ways I can do this?

Vimanyu
  • 625
  • 2
  • 9
  • 24
TheCo
  • 51
  • 1
  • 3
  • You'd better stay away dealing with raw pointers at all. For the majority of use cases you don't need them anyways. Thank god, standard C++ comes with [_Containers_](http://en.cppreference.com/w/cpp/container) and [_Dynamic memory management_](http://en.cppreference.com/w/cpp/memory), just stick with that stuff. –  Feb 06 '18 at 23:40
  • 1
    A zero pointer is obvious. But there's no way to detect a pointer to invalid memory in the modern multi-threaded world where another thread could deallocate (even unmap, using an OS API) memory between your "test" and your "access". In a single threaded program you can do better. But, testing to see if it points to a valid object not just valid memory is really not possible. – davidbak Feb 06 '18 at 23:44
  • Pointers are one way only. They point to something, but there is no backchannel to let you know when that something no longer exists. Think of the insane amount of book keeping that would require. Every object in the system could have N other objects pointing to it. Storing that would be insane. Sending out and handling all of notifications would also be insane. That said, take a look at `std::weak_ptr` for something that kinda-sorta comes close. – user4581301 Feb 06 '18 at 23:52
  • Use `std::unique_ptr`. It will either point at something else it will be null. – Galik Feb 06 '18 at 23:58
  • @Galik: Unless your program has undefined behavior in it... which is the only reason I can think of for asking this question. – Ben Voigt Feb 07 '18 at 00:19

0 Answers0