我正在尝试写入通过 VirtualAlloc() 分配的内存位置,然后从中读取,作为一个简单的练习。下面是我的代码:
#include<stdio.h>
#include<Windows.h>
int main(void) {
//allocate memory
WCHAR text[512];
void* mem = VirtualAlloc(NULL,sizeof(WCHAR)*512,MEM_RESERVE| MEM_COMMIT,PAGE_READWRITE);
if (mem == NULL) {
printf("Memory allocation failed\n");
return 0;
}
//query user to store text into memory
printf("Mem address: 0x%p\nEnter text to copy to pointer mem: ",mem);
scanf_s("%S",text,_countof(text));
wcscpy_s((WCHAR*)mem, sizeof(text)/sizeof(WCHAR), text);
//read text from memory location
WCHAR readText[512];
wcscpy_s(readText,_countof(readText),(WCHAR *)mem);
wprintf(L"What was in mem: %ls",readText);
VirtualFree(mem, 0, MEM_RELEASE); // Release the allocated memory
return EXIT_SUCCESS;
}
但是,当我输入
Hello world!
作为输入时,它只输出 Hello
而不是输入的内容。以下是控制台输出:
Mem address: 0x000001EB5E1A0000
Enter text to copy to pointer mem: hello world!
What was in mem: hello