You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用wcscpy_s从VirtualAlloc分配内存读取WCHAR时内容截断问题

问题解决:VirtualAlloc内存读写时输入带空格字符串只读取部分内容

你用VirtualAlloc分配内存后读写字符串,输入Hello world!却只输出Hello,问题根源在输入读取环节。

问题原因

scanf_s("%S", text, _countof(text))里的%S格式符(对应宽字符字符串)会把空格、制表符、换行符当作输入分隔符,读取到第一个空格就停止。所以输入hello world!时,text里只存了hello,后续的world!根本没被读入,最终输出自然只有hello。

解决方案

改用fgetws读取整行宽字符输入,它可以读取包括空格在内的所有字符直到换行符,之后手动去掉输入末尾的换行符(fgetws会把换行符也读进字符串)。

修改后的完整代码

#include<stdio.h>
#include<Windows.h>
#include<string.h>  // 用于wcsrchr函数

int main(void) {
    // 分配内存
    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;
    }
    // 提示用户输入文本
    printf("Mem address: 0x%p\nEnter text to copy to pointer mem: ", mem);
    
    // 读取整行宽字符输入(包含空格)
    fgetws(text, _countof(text), stdin);
    // 移除末尾的换行符(如果存在)
    WCHAR* newline = wcsrchr(text, L'\n');
    if (newline != NULL) {
        *newline = L'\0';
    }

    // 将输入文本复制到VirtualAlloc分配的内存
    wcscpy_s((WCHAR*)mem, sizeof(text)/sizeof(WCHAR), text);
    
    // 从分配的内存中读取文本并输出
    WCHAR readText[512];
    wcscpy_s(readText, _countof(readText), (WCHAR *)mem);
    wprintf(L"What was in mem: %ls\n", readText);
    VirtualFree(mem, 0, MEM_RELEASE);  // 释放分配的内存
    return EXIT_SUCCESS;
}

关键改动说明

  • 用fgetws(text, _countof(text), stdin)替代scanf_s,实现整行输入读取(支持含空格的字符串)
  • 用wcsrchr定位字符串末尾的换行符,替换为字符串结束符\0,避免输出时带多余换行
  • 调整了输出语句的换行符,让控制台输出格式更清晰

内容的提问来源于stack exchange,提问作者user2494337

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 17:22:24