如何在C ++中将值放入VirtualAlloc分配的内存中?

时间:2018-11-28 22:26:51

标签: c++ winapi memory-management virtualalloc

我正在尝试学习如何使用VirtualAlloc和VirtualFree函数。

我已经阅读了VirtualAllocVirtualFree上的msdn参考,并了解了如何使用它们(至少在基本级别上)。

问题是我找不到如何将值放入分配的内存中。

我试图编写一个简单的c ++应用程序,该应用程序是:
1.使用VirtualAlloc保留3000字节的内存。
2.提交保留的内存。
3.将char类型值放入提交的内存中。
4.使用VirtualFree释放内存。

#include<windows.h>

int main() {

 LPVOID ptr = VirtualAlloc(NULL,3000,MEM_RESERVE,PAGE_READWRITE); //reserving memory

 ptr = VirtualAlloc(ptr,3000,MEM_COMMIT,PAGE_READWRITE); //commiting memory

    int i;
    for(i=0; i<3000; i++) {
       ptr[i]= 'a';         //failed attempt to fill the allocated memory with 'a'
    }

 VirtualFree(ptr, 0, MEM_RELEASE); //releasing memory

return 0;
}

这当然给出了:

[Warning] pointer of type 'void *' used in arithmetic [-Wpointer-arith]. 
[Error] 'LPVOID {aka void*}' is not a pointer-to-object type.

所以我的问题是我该如何正确地将值放入c ++中VirtualAlloc分配的内存中?

我也找到了this的示例,但是它没有编译,因此无法正常工作。

1 个答案:

答案 0 :(得分:-1)

@Igor Tandetnik的回复有效

#include<windows.h>

int main() {
 LPVOID ptr = VirtualAlloc(NULL,3000,MEM_RESERVE,PAGE_READWRITE); //reserving memory
 ptr = VirtualAlloc(ptr,3000,MEM_COMMIT,PAGE_READWRITE); //commiting memory
 memset(ptr, 'a', 3000);
 VirtualFree(ptr, 0, MEM_RELEASE); //releasing memory
return 0;
}

感谢您的答复。

[编辑] 还尝试将其强制转换为char *,并且也可以使用。
再次感谢。

#include<windows.h>
int main() {
 int i;
 LPVOID ptr = VirtualAlloc(NULL,3000,MEM_RESERVE,PAGE_READWRITE); //reserving memory
ptr = VirtualAlloc(ptr,3000,MEM_COMMIT,PAGE_READWRITE); //commiting memory  
char* char_ptr = static_cast<char*>(ptr);

for(i=0;i<3000;i++){
    char_ptr[i] = 'a';  
} 

VirtualFree(ptr, 0, MEM_RELEASE); //releasing memory

return 0;
}

[edit] [2]
@DavidHeffernan表示处理返回值:

#include<windows.h>  
#include<iostream>
using namespace std; 

int main() {
size_t in_num_of_bytes,i;
cout<<"Please enter the number of bytes you want to allocate:";
cin>>in_num_of_bytes;                                      

LPVOID ptr = VirtualAlloc(NULL,in_num_of_bytes,MEM_RESERVE | MEM_COMMIT,PAGE_READWRITE); //reserving and commiting memory

if(ptr){
    char* char_ptr = static_cast<char*>(ptr);
    for(i=0;i<in_num_of_bytes;i++){ //write to memory
        char_ptr[i] = 'a';
    }

    for(i=0;i<in_num_of_bytes;i++){ //print memory contents
        cout<<char_ptr[i];
    }

    VirtualFree(ptr, 0, MEM_RELEASE); //releasing memory    
}else{
    cout<<"[ERROR]:Could not allocate "<<in_num_of_bytes<<" bytes of memory"<<endl; 
}

return 0;
}