How to check whether a memory address is valid

29 07 2015


As a programmer, some time we may need to check whether the specified memory block is within our application’s memory space. How can we do it?

Windows provides an API AfxIsValidAddress for same.

BOOL AfxIsValidAddress(const void* lp, UINT nBytes, BOOL bReadWrite = TRUE);

Parameters
lp : Points to the memory address to be tested.
nBytes : Contains the number of bytes of memory to be tested.
bReadWrite : Specifies whether the memory is both for reading and writing (TRUE) or just reading (FALSE).

Return Value
AfxIsValidAddress() returns TRUE if the passed parameter points to at least nBytes of accessible memory. If bReadWrite is TRUE, the memory must be writable; if bReadWrite is FALSE, the memory may be const.

Advertisements