gpt4 book ai didi

c++ - 释放中间变量

转载 作者:行者123 更新时间:2023-11-30 01:24:22 25 4
gpt4 key购买 nike

我在检查源代码时看到这个 for 循环:

for (int i=0; i < result1.length(); i++) {
unsigned char *buff = ascii_to_utf8((unsigned char)result1.at(i));
result.append((char*)buff);
free (buff);
}

已更改为:

for (int i=0; i < result1.length(); i++)
result.append((char*)ascii_to_utf8((unsigned char)result1.at(i)));

我能看到的唯一区别是在第二个代码中没有中间变量。

我的问题是,我看不到的两个代码片段之间有区别吗?在第二个代码中没有什么可以free的吗?

------------ 编辑------------这是 ascii_to_utf8 的源代码:

unsigned char* InvoiceXML::ascii_to_utf8(unsigned char c)
{
unsigned char *out;

if(c < 128)
{
out = (unsigned char *)calloc(2, sizeof(char));
out[0] = c;
out[1] = '\0';
}
else
{
out = (unsigned char *)calloc(3, sizeof(char));
out[0] = (c >> 6) | 0xC0;
out[1] = (c & 0x3F) | 0x80;
out[2] = '\0';
}

return out;
}

最佳答案

这取决于 ascii_to_utf8 的作用;它几乎肯定会分配内存,在这种情况下你确实需要那里的“免费”。所以第二个片段会泄漏内存。

关于c++ - 释放中间变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13746806/

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