c/c++如何判断指针无效?如NULL,0xcccccccc,0xfeeefeee,野指针等

清泛原创
c/c++如何判断指针无效?不仅仅是NULL的判断,有时由于指针释放没有赋NULL,指针会变成野指针或诸如0xcccccccc,0xfeeefeee形式的无效指针,那么此时如何判断指针是否有效呢?

AfxIsValidAddress
// Allocate a 5 character array, which should have a valid memory address.
char* arr = new char[5];

// Create a null pointer, which should be an invalid memory address.
char* null = (char*)0x0;

ASSERT(AfxIsValidAddress(arr, 5));
ASSERT(!AfxIsValidAddress(null, 5));
IsBadWritePtr, IsBadReadPtr
BOOL AFXAPI AfxIsValidAddress(const void* lp, UINT nBytes,
BOOL bReadWrite /* = TRUE */)
{
// simple version using Win-32 APIs for pointer validation.
return (lp != NULL && !IsBadReadPtr(lp, nBytes) &&
(!bReadWrite || !IsBadWritePtr((LPVOID)lp, nBytes)));
}

指针无效 0xcccccccc 0xfeeefeee 野指针

分享到:
评论加载中,请稍后...
创APP如搭积木 - 创意无限,梦想即时!
回到顶部