[英]Char* related memory leak
我正在運行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”
輸出是:您說的:你好
並且沒有發現泄漏。
hello
包含空格,因此strcspn
返回strlen(ClientInput)
,因此您進入了第一個分支。 在該分支中, verb
和args
不會動態分配,因此不會泄漏。
但是請注意,在“可能已分配”的內存中放置一個變量點通常非常危險,因為很難確定是否應釋放該變量。 因此,您應該在兩個分支中都使用new
,並在末尾無條件釋放兩個變量。 或者,更好的是,使用std::string
並完全避免此問題。
輸入為hello
時,兩個char *
元素verbs
或args
均未分配,因為:
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
strcspn(ClientInput, " ")
的輸出與strlen(ClientInput)
相同,因此不會執行new[]
操作,也不會分配內存。
您如何判斷是否需要釋放verb
和args
? 不知道是否釋放內存很危險。
為什么兩個char *數組不創建泄漏?
它們僅在您將new
運算符的結果分配給它們時才起作用(在這種情況下,Valgrind應該通知您)。 如果為常量字符串分配常量字符串,則不會有內存泄漏-常量字符串在程序的整個生命周期中都有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.