2013-02-09 39 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