Search code examples
c++c++11mfcplatform-independentafx

What is the equivalent standard function of the "AfxIsValidAddress" function?


I was using an MFC-project, that shall be proted in a platform-independent environment, using std-function instead of MFC/AFX.

For example: instead CString the std::string, instead CMutex the std::mutex will be used.

What is the platform-independet, C++11 std::-equivalent of the MFC function "AfxIsValidAddress"?


Solution

  • There is not something similar to AfxIsValidAddress() in the standard library and it appears that the function doesn't actually do that much validation anyway.

    See AfxIsValidAddress (and Others) Don’t Work as Advertised which says the function ends up just doing a check against NULL. It also has this to say about the family of valid address check functions:

    There are several Win32 API similar in functionality: IsBadWritePtr, IsBadHugeWritePtr, IsBadReadPtr, IsBadHugeReadPtr, IsBadCodePtr, IsBadStringPtr. It has been known since at least 2004 that these functions are broken beyond repair and should never be used. The almighty Raymond Chen and Larry Osterman both discuss the reasons in detail, so just a short rehash: IsBad*Ptr all work by accessing the tested address and catching any thrown exceptions. Problem is that a certain few of these access violations (namely, those on stack guard pages) should never be caught – the OS uses them to properly enlarge thread stacks.

    I think it is better to just follow standard C++ procedures to check that a pointer is not a nullptr or better yet to limit the use of pointers as much as possible.