我正在运行Valgrind检查我的代码是否有内存泄漏。 Valgrind没有显示任何泄漏,但我有一段代码,我认为应该导致泄漏,我不明白变量是如何被清理或Valgrind没有捕获它。为什么两个char *数组不会产生泄漏?
void BasicEngine::ConnectionInput(int ConnectionId, const char* ClientInput)
{
// find client assignment to this ConnectionId
Client* thisClient = this->ClientFind(ConnectionId);
int SpaceLocation = strcspn(ClientInput," ");
char* verb;
char* args;
if(SpaceLocation == strlen(ClientInput))
{
verb = (char*)ClientInput;
args = (char*)"";
}
else
{
verb = new char[SpaceLocation+1];
args = new char[strlen(ClientInput)-SpaceLocation+1];
sscanf(ClientInput,"%s %[^\n]",verb,args);
}
if(thisClient != NULL)
{
// ... client is always null, this is not being reached at the moment.
}
else
{
if(this->refCmdHandler != NULL)
if(this->refCmdHandler->cmdHandler(ConnectionId,ClientInput))
return;
}
this->refServer->TransmitNL(ConnectionId,"Invalid Command.");
}
bool BasicCmdProc::cmdHandler(int ConnectionId, string ClientInput)
{
Transmit(ConnectionId,string("You Said: ") + ClientInput);
return true;
}
如果我输入'hello'
输出是:你说:你好
并且没有检测到泄漏。
答案 0 :(得分:3)
hello
不包含空格,因此strcspn
会返回strlen(ClientInput)
,因此您将获取第一个分支。在该分支中,verb
和args
未动态分配,因此没有泄漏。
但是,请注意,在“可能已分配”的内存中设置变量点通常非常危险,因为要确定是否应该释放变量将更加困难。因此,您应该在两个分支中使用new
,并在最后无条件地释放两个变量。或者,更好的是,使用std::string
并完全避免这个问题。
答案 1 :(得分:0)
当输入为char *
时,两个verbs
元素args
或hello
均未分配,因为:
int SpaceLocation = strcspn(ClientInput," ");
char* verb;
char* args;
if (SpaceLocation == strlen(ClientInput))
{
verb = (char*)ClientInput;
args = (char*)"";
}
else
{
verb = new char[SpaceLocation+1];
args = new char[strlen(ClientInput)-SpaceLocation+1];
sscanf(ClientInput,"%s %[^\n]",verb,args);
}
strcspn(ClientInput, " ")
的输出,即SpaceLocation
,与strlen(ClientInput)
相同,因此new[]
操作不会执行,也不会分配内存。
您如何判断是否需要发布verb
和args
?不知道是否释放记忆是危险的。
答案 2 :(得分:0)
为什么两个char *数组不会产生泄漏?
他们只在您将new
运算符的结果分配给他们时才会这样做(在这种情况下,Valgrind应该通知您)。如果为它们分配常量字符串,那么就没有内存泄漏 - 在程序的整个生命周期内,常量字符串仍然存在。