2013-02-09 35 views
0

我正在運行Valgrind檢查我的代碼是否有內存泄漏。 Valgrind沒有顯示任何泄漏發生,但我有一段代碼,我認爲應該導致泄漏,我不明白如何清理變量或Valgrind沒有捕捉它。爲什麼兩個char *數組不會產生泄漏?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; 
} 

如果我在 '你好'

輸出輸入:你說:你好

,並沒有檢測到泄漏。

+1

爲什麼你使用的數組不是'vector' s呢? – 2013-02-09 23:46:29

+0

你是不是指'string',@BartekBanachewicz?我想,'vector '是處理字符串的一種不尋常的方式。 – 2013-02-09 23:48:46

+0

這可能是深夜+我最近做了太多奇怪的IO。 – 2013-02-09 23:51:48

回答

0

無論兩個char *元件verbsargs被分配的,當輸入是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[]操作並沒有分配內存。

如何判斷是否需要發佈verbargs?不知道是否釋放內存是危險的。

0

爲什麼兩個char *數組不會產生泄漏?

它們只會在您將new運算符的結果賦予給它們(並且在這種情況下,Valgrind應該通知您)時執行。如果給它們分配常量字符串,那麼就沒有內存可以泄漏 - 在程序的整個生命週期內,常量字符串都是活着的。

3

hello不包含空格,所以strcspn返回strlen(ClientInput),所以你拿第一個分支。在那個分支中,verbargs不是動態分配的,所以沒有泄漏。

但是請注意,在「可能分配」的內存中有一個變量點通常是非常危險的,因爲確定變量是否應該被釋放會更難。因此,您應該在兩個分支中使用new,並在最後無條件釋放這兩個變量。或者,更好的是,使用std::string s並完全避免這個問題。

+0

+1對'可能分配'內存的評論。 – 2013-02-09 23:49:33

+0

+1同樣的評論。 – WhozCraig 2013-02-10 00:45:21

+0

我嘗試了'hello world'作爲輸入,但仍然得到了沒有內存泄漏的相同結果。可以將char *數組傳遞給字符串參數對此有一些影響嗎?它是我能想出的唯一的東西。 – user1908813 2013-02-10 20:37:04