0

Is there a way to check a pointer's validity besides the common assert(NULL != ptr)? I tried the following to intentionally provoke an "access error" so i will be alerted early, not lately when the pointer is accessed in some nested code:

#if !defined _NDEBUG || defined _DEBUG
  #define _check_ptr(ptr, type) do{type x; assert(NULL != ptr); x = *ptr;}while(0)
#else
  #define _check_ptr(ptr, type)
#endif

Desired usecase:

void func(int *ptr){
    _check_ptr(ptr, int);
    
    if (NULL != ptr){ // Still check in release
        ...
    }
}

As a precondition it would be perfectly acceptable to rely upon the IDE throwing me into the debugger on access error. In my case I will not run the debug build from command line or from somewhere outside the IDE.

TylerH
  • 20,799
  • 66
  • 75
  • 101
  • 1
    make your variable static volatile or the compiler could optimize the assignment. and the pointer could be invalid and not crash when de-referenced (just unallocated memory area?) – Jean-François Fabre Nov 19 '20 at 10:12
  • That's an interesting point i did not thought of! – Wör Du Schnaffzig Nov 19 '20 at 10:13
  • Remember that invalid pointer dereference leads to undefined behavior, and that might not always result in a crash. Especially, reading a value using pointer dereference could seem to work if the (random) memory being pointed to happens to be mapped to the process. In short, the only way sure-fire check is for null pointers. If you want to catch other errors, use a lot of testing and memory debuggers like Valgrind or other alternative on Windows. – Some programmer dude Nov 19 '20 at 10:17
  • 1
    These things need to be checked statically by the compiler or a static analyser. Specifically, are all pointers initialized before used. – Lundin Nov 19 '20 at 10:35
  • I also tried the obsolete functions `IsBadReadPtr/IsBadWritePtr(ptr, sizeof(*ptr))` from the windows API. However, they did not have the chance to fail because the access violation occured beforehand. @Lundin: The compiler does it's best in detecting such errors beforehand by issuing warnings. However the warnings often show up earliest on complete rebuild, esp. when dealing with legacy code. – Wör Du Schnaffzig Nov 19 '20 at 10:36

0 Answers0