Renkokuken GO Moderator
Reputation: 4
Joined: 22 Oct 2006 Posts: 3249
|
Posted: Fri Oct 12, 2007 2:48 pm Post subject: Memory Management Functions. |
|
|
I'll make some clear examples of using most memory management functions.
We'll go over :
VirtualProtect
VirtualAlloc
VirtualFree
VirtualQuery
In the following languages :
Delphi
(C++ Tomorrow)
__________________________________________________________
Delphi Users : I'll go over these functions with you first!
VirtualAlloc :
| Code: | VAR nAddress : Pointer; //Declare the variables, nAddress will be the pointer to the new allocated page.
Size : Cardinal; //Size, in bytes, of the allocated page.
begin
Size := 4096; //4096 is a decent size for a new page.
nAddress := VirtualAlloc(NIL, // The first parameter is NIL, since we don't require the memory at a set address.
Size, //Size of the allocated page.
MEM_COMMIT, //Allocates physical storage in memory on disk for the specified reserved memory pages.
PAGE_READWRITE); //Give the page read and write access to the committed region of pages.
// If all went well, nAddress should point to the newly allocated memory.
end; |
VirtualQuery :
| Code: | var MBI : MEMORY_BASIC_INFORMATION; //Contains information about a range of pages in the virtual address space of a process.
begin
VirtualQuery(nAddress, //We'll use the pointer from the VirtualAlloc above.
MBI, //Pointer to the MEMORY_BASIC_INFORMATION structure.
sizeof(MBI)); //Sizeof() retrieves the general size of the variable, in this case MBI.
//If no errors occured, the MBI structure should hold information on the page allocated by VirtualAlloc.
end; |
VirtualProtect :
| Code: | VAR OldRights : DWORD; //Declare this, we'll need it later for VirtualProtect.
begin
VirtualProtect(MBI.BaseAddress, //Since VQ filled MBI's structure, MBI.BaseAddress is a pointer to the allocated page.
Size, //We'll need the size of the memory to change protections, so we'll use the variable from before.
PAGE_EXECUTE_READWRITE, //Give execute/read/write access to the committed region of pages.
@OldRights); //Pointer to a DWORD that will hold the old protection for replacing it later.
//If it all went well, VirtualProtect should have changed the protections in the page.
end; |
VirtualFree :
| Code: | begin
VirtualFree(MBI.BaseAddress, //Starting address for the page to be deallocated.
0, //"0" will deallocate the entire page, if the starting address is inbetween 2 pages, both will be deallocated.
MEM_RELEASE); //Release the memory in the specified page, afterwards, the page is in a free-state.
//If all went well, the page allocated by VirtualAlloc should be released.
end; |
That's all for now, I'll add more later today or tomorrow, I'm sick currently.
|
|