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

使用WinHTTP开发时修改URL_COMPONENT中LPWSTR值触发SIGSEGV错误求助

问题原因与解决方案

你遇到的SIGSEGV是因为字符串字面量存储在只读内存区域,代码里的L"America, England, Belgium"属于宽字符串字面量,程序加载时会被放到只读数据段(比如Windows里的.rdata段),当你通过LPWSTR指针去修改这个区域的内容时,会触发内存访问保护,导致段错误。

解决办法

方法1:将字符串复制到可写堆内存

使用malloc分配足够的内存,把字面量复制过去再修改:

#include <windows.h>
#include <stdio.h>
#include <wchar.h>
#include <stdlib.h>

int main(int argc, char const *argv[])
{
    LPCWSTR countryLiteral = L"America, England, Belgium";
    // 计算所需内存(包含终止符)
    size_t len = wcslen(countryLiteral) + 1;
    LPWSTR country = (LPWSTR)malloc(len * sizeof(WCHAR));
    if (country == NULL) {
        printf("内存分配失败\n");
        return 1;
    }
    wcscpy_s(country, len, countryLiteral);
    
    size_t pos = 0;
    while(country[pos] != L',') pos++;
    country[pos] = L'\0';
    printf("%ls\n", country);
    
    free(country); // 记得释放堆内存
    return 0;
}

方法2:使用栈上的WCHAR数组

直接声明数组存储字符串,栈内存是可写的:

#include <windows.h>
#include <stdio.h>
#include <wchar.h>

int main(int argc, char const *argv[])
{
    WCHAR country[] = L"America, England, Belgium";
    size_t pos = 0;
    while(country[pos] != L',') pos++;
    country[pos] = L'\0';
    printf("%ls\n", country);
    return 0;
}

对应到WinHTTP的URL_COMPONENT场景

在处理URL_COMPONENTS时,如果你要修改结构体里的LPWSTR成员,同样要确保该指针指向的是可写内存。比如从URL_COMPONENTS获取到的字符串如果是来自WinHTTP的只读缓冲区,需要先复制到自己分配的可写内存再修改,避免直接修改只读区域。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 10:25:55