Determining if Memory Pointer is Valid - C++

Posted by Jim Fell on Stack Overflow See other posts from Stack Overflow or by Jim Fell
Published on 2011-01-04T16:03:29Z Indexed on 2011/01/04 17:54 UTC
Read the original article Hit count: 174

Filed under:
|
|
|

It has been my observation that if free( ptr ) is called where ptr is not a valid pointer to system-allocated memory, an access violation occurs. Let's say that I call free like this:

LPVOID ptr = (LPVOID)0x12345678;
free( ptr );

This will most definitely cause an access violation. Is there a way to test that the memory location pointed to by ptr is valid system-allocated memory?

It seems to me that the the memory management part of the Windows OS kernel must know what memory has been allocated and what memory remains for allocation. Otherwise, how could it know if enough memory remains to satisfy a given request? (rhetorical) That said, it seems reasonable to conclude that there must be a function (or set of functions) that would allow a user to determine if a pointer is valid system-allocated memory. Perhaps Microsoft has not made these functions public. If Microsoft has not provided such an API, I can only presume that it was for an intentional and specific reason. Would providing such a hook into the system prose a significant threat to system security?

Situation Report

Although knowing whether a memory pointer is valid could be useful in many scenarios, this is my particular situation:

I am writing a driver for a new piece of hardware that is to replace an existing piece of hardware that connects to the PC via USB. My mandate is to write the new driver such that calls to the existing API for the current driver will continue to work in the PC applications in which it is used. Thus the only required changes to existing applications is to load the appropriate driver DLL(s) at startup. The problem here is that the existing driver uses a callback to send received serial messages to the application; a pointer to allocated memory containing the message is passed from the driver to the application via the callback. It is then the responsibility of the application to call another driver API to free the memory by passing back the same pointer from the application to the driver. In this scenario the second API has no way to determine if the application has actually passed back a pointer to valid memory.

© Stack Overflow or respective owner

Related posts about c++

Related posts about memory