I am trying to write to a memory location allocated via VirtualAlloc(), and then read from it as a simple exercise. Below is my code:
#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;
}
However, when I type in Hello world!
as input, it only outputs Hello
instead of what was input. Below is the console output:
Mem address: 0x000001EB5E1A0000
Enter text to copy to pointer mem: hello world!
What was in mem: hello