使用 wcscpy_s 从内存位置读取 WCHAR

问题描述 投票:0回答:1

我正在尝试写入通过 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
c winapi
1个回答
0
投票

scanf_s 从标准输入流读取格式化数据,默认由空格字符分隔

要读取不由空格字符分隔的字符串,需要一组 括号 ([ ]) 中的字符可以替换 s(字符串) 输入字符。

例如

wscanf_s(L"%[^\n]", text, _countof(text));

另请参阅https://stackoverflow.com/a/13728449/15511041

© www.soinside.com 2019 - 2024. All rights reserved.