gpt4 book ai didi

c++ - Valgrind——可能丢失警告

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:54:03 25 4
gpt4 key购买 nike

我有以下代码:

std::string myName = "BLABLABLA";

//check if there are illegal characters
for (unsigned int i = 0; i < myName.length(); i++)
{
const char& c = myName[i];
if (!(isalnum(c) || (c == '_') || (c == '-')))
{
return 0;
}

}

这是 valgrind 在“const char& c = myName[i];”行的输出

==17249== 51 bytes in 1 blocks are possibly lost in loss record 116 of 224
==17249== at 0x4C2714E: operator new(unsigned long) (vg_replace_malloc.c:261)
==17249== by 0x602A498: std::string::_Rep::_S_create(unsigned long, unsigned long,
std::allocator<char> const&) (in /usr/lib64/libstdc++.so.6.0.16)
==17249== by 0x602A689: std::string::_M_mutate(unsigned long, unsigned long,
unsigned long) (in /usr/lib64/libstdc++.so.6.0.16)
==17249== by 0x602AFB5: std::string::_M_leak_hard() (in
/usr/lib64/libstdc++.so.6.0.16)
==17249== by 0x602B0A4: std::string::operator[](unsigned long) (in /
/usr/lib64/libstdc++.so.6.0.16)

我看不出有什么不对...

最佳答案

是的,这是可怕的 COW 实现!您还可以像这样强制使用 const(因此是非变异的)重载:

std::string const myName = "BLABLABLA";

//check if there are illegal characters
for (unsigned int i = 0; i < myName.length(); i++)
{
const char& c = myName[i];
if (!(isalnum(c) || (c == '_') || (c == '-')))
{
return 0;
}
}

或者(如果不想修改原来的字符串类型):

std::string myName = "BLABLABLA";
std::string const &cref = myName;
//check if there are illegal characters
for (unsigned int i = 0; i < myName.length(); i++)
{
const char& c = cref[i];
if (!(isalnum(c) || (c == '_') || (c == '-')))
{
return 0;
}
}

等等


COW reference ,因为我知道我已经在某个地方写了一些关于它的东西。

关于c++ - Valgrind——可能丢失警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12604376/

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