gpt4 book ai didi

c - 为什么这个函数在释放内存时总是崩溃?

转载 作者:太空宇宙 更新时间:2023-11-04 00:31:55 27 4
gpt4 key购买 nike

int gb2Utf8(const char* source, int sourceLen, void *target, int targetLen)
{
int result = 0;
int bufLen = strlen(source) * 2;
wchar_t *buffer = (wchar_t *)malloc(bufLen);
if (!buffer)
{
result = 1;
goto RETURN;
}

//GB18030 code page: 54936
int m2wResult = MultiByteToWideChar(54936, MB_ERR_INVALID_CHARS, source, -1, buffer, bufLen);
if (!m2wResult)
{
result = 2;
goto RETURN;
}

int w2mResult = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, buffer, -1, (char *)target, targetLen, NULL, NULL);
if (!w2mResult)
{
result = 3;
goto RETURN;
}

RETURN:
free(buffer);
return result;
}

当程序运行到free(buffer)时,它会崩溃,但我不知道为什么。
如果修改bufLen为常量值,或者去掉MultiByteToWideChar函数,不会崩溃,我也不知道为什么。这是崩溃时的调用堆栈:

msvcr100d.dll!_free_dbg_nolock(void * pUserData, int nBlockUse) Line 1376 + 0x3b bytes C++
msvcr100d.dll!_free_dbg(void * pUserData, int nBlockUse) Line 1265 + 0xd bytes C++
msvcr100d.dll!free(void * pUserData) Line 49 + 0xb bytes C++
New.exe!gb2Utf8(const char * source, int sourceLen, void * target, int targetLen) Line 156 + 0xc bytes C++
New.exe!wWinMain(HINSTANCE__ * hInstance, HINSTANCE__ * hPrevInstance, wchar_t * lpCmdLine, int nCmdShow) Line 29 + 0x11 bytes C++
New.exe!__tmainCRTStartup() Line 547 + 0x2c bytes C
New.exe!wWinMainCRTStartup() Line 371 C
kernel32.dll!7509339a()
[Frames below may be incorrect and/or missing, no symbols loaded for kernel32.dll]
ntdll.dll!77979ef2()
ntdll.dll!77979ec5()

最佳答案

也许对于缓冲区,您也需要为 NULL 终止符分配内存:

int bufLen = strlen(source) * 2 + 2;

关于c - 为什么这个函数在释放内存时总是崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11554091/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com