15.6 Changing protection Properties
(1) Vritualprotect function
Parameters |
Describe |
PVOID pvaddress |
Point to the memory base address for which you want to modify properties |
size_t dwsize |
The size of the zone, in bytes |
DWORD Flnewprotect |
Page_* (except Page_writecopy, page_excute_writecopy) |
Pdword Pfloldprotect |
Returns the original protection property, sometimes although it is not necessary to return this information, but must pass in a valid pfloldprotect parameter |
(2) Attention points
The ① protection property is associated with the entire physical storage page and cannot specify a protection property for one byte.
② when several contiguous physical storage pages span different regions, virtualprotect cannot change their protection properties. If you have adjacent regions and want to change the protection properties of contiguous pages across regions, you must call the function multiple times.
"VirtualProtect Program"
#include <windows.h>#include<tchar.h>#include<time.h>#include<locale.h>#defineMemsize (1024*1024)int_tmain () {_tsetlocale (Lc_all, _t ("CHS")); Srand ((unsigned) time (NULL)); //1. Reserve and submit memory (1MB)void* precv = VirtualAlloc (NULL, memsize, Mem_reserve |Mem_commit, Page_readwrite); if(Precv! =NULL) {_tprintf (_t ("Allocate%DKB memory successfully! \ n"), Memsize/1024x768); } Else{_tprintf (_t ("Request%DKB Memory failed! (Error code:%d) \ n"), Memsize/1024x768, GetLastError ()); return 0; } //2. Memory Write Operation float* Pfarray = (float*) Precv; for(inti =0; I < memsize/sizeof(float); i++) {Pfarray[i]=1.0f* (rand ()%Ten); } _tprintf (_t ("start at [0x%X] and write%d data of type float successfully! \ n"), Precv,memsize/sizeof(float));
//3. Change the Protection property to read-onlyDWORD Dwoldprotect =0; BOOL bOk= VirtualProtect (Precv, Memsize, Page_readonly, &dwoldprotect); if(bOk) {_tprintf (_t ("successfully modified the requested memory space as a read-only property! \ n")); } Else{_tprintf (_t ("An attempt to modify the requested memory space for a read-only property failed! (Error code:%d) \ n"), GetLastError ()); return 0; }
//4. Read all values to sum floatFsum =0.0f; for(inti =0; I < memsize/sizeof(float); i++) {fsum+=Pfarray[i]; } _tprintf (_t ("%d random number sum is%f\n"), Memsize/sizeof(float), fsum); //5. An attempt was made to write the 10th element, which would cause an exception__try{pfarray[9] =0.0f; }__except (exception_execute_handler) {_tprintf (_t ("illegal access to memory, attempting to write data in read-only memory!\n")); } //6. Direct ReleaseBOk = VirtualFree (PRECV,0, mem_release); _tprintf (_t ("Free Memory%s! \ n"), BOk? _t ("Success"): _t ("failed")); return 0;}
15th. Using virtual memory in your application (2)