2016-01-31 65 views
-3
void IRC_MESSAGE::GetHeader() 
{ 
    int find_first = this->FindChar(this->MessageText, ':'); 
    int find_second = 0; 
    if(find_first > -1) { 
     find_second = this->FindChar(this->MessageText+(find_first + 1), ':'); 
     if(find_second > -1) { 
      //dies here on this message 
      //this->MessageText = ":irc.betawarz.com 001 Fatal-Error[B] :Welcome to the Beta IRC Network Fatal-Error[B][email protected]" 
      this->Header = (char *)malloc((find_second - find_first) + 1); 
      ZeroMemory(this->Header, (find_second - find_first) + 1); 
      memcpy(this->Header, this->MessageText + (find_first + 1), 
        (find_second - (find_first + 1))); 
      return; 
     } else { 
      this->Header = (char *)malloc(find_first + 1); 
      ZeroMemory(this->Header, find_first + 1); 
      if(find_first == 0) { 
       this->Header = ""; 
      } else { 
       memcpy(this->Header, this->MessageText, find_first); 
      } 
      return; 
     } 
    } 
    this->Header = "NA"; 
    return; 
} 
----------------------------- 
char *Header; char *MessageText;  

int FindChar(char *,char),只返回所述值的第一個索引,如果沒有找到,則返回-1。C++ 2010,堆的腐敗?

我的問題在這裏是我的標記,它死在這裏,當它有下面的MessageText。 它崩潰說:這可能是由於堆的腐敗,這表明ApplicationX.exe或它已加載的任何DLL中的錯誤。 但我在此之前得到3或4條消息,不會折騰這次崩潰。 其他人在這裏可以看到我的問題。

+2

在C++中使用'new'和'delete',而不是'malloc'和'free'。 – Downvoter

+0

您不需要代碼中的所有'this->' –

+0

您是否正在使用MFC? – stackptr

回答

0

的一個問題是在這裏

 this->Header = (char *)malloc((find_second - find_first) + 1); 
     ZeroMemory(this->Header, (find_second - find_first) + 1); 
     memcpy(this->Header, this->MessageText + (find_first + 1), 
       (find_second - (find_first + 1))); 

malloc()分配find_second-find_first+1字符的字符。 memcpy()請致電this->MessageText + find_first + 1複製find_second - find_first - 1個字符。 find_firstfind_second的最小值都爲零,在這種情況下,find_second-find_first - 1-1,作爲int

但是,memcpy()的第三個參數是size_t類型,它是unsigned類型。當轉換爲size_t時,-1的值因此是最大值a size_t可以表示(例如,如果size_t是32位類型,則爲4294967295)。公平地說,在某些情況下複製4294967295不是您的意圖 - 特別是,前面的malloc()分配的大小爲1

另一個問題是,語句this->Header = "";導致以前的值this->Header(由前面的malloc()返回)丟失。至少,這是一個內存泄漏。如果其他代碼調用(實際上)free(this->Header),結果是未定義行爲,因爲字符串文字""未使用malloc()進行分配。

更一般地,考慮使用std::string類型。它有一些有用的工具,並在需要時乾淨地附加字符串 - 而不會像您所示的那樣出現內存管理錯誤。除非你真的需要它,否則不要使用this->。在你的代碼中,它讓事情變得不太清晰,幾乎肯定不需要。

+0

它所做的是獲取:和之間的字符串值,如果它找到第二個字符串,它將進入else語句並返回字符串從0到第一個:如果它是0,則返回第一個:anyways它返回標題爲「」。 總會有至少1個。 –

+0

@Jaime你在這裏沒有深度。這不是如何編寫C++。考慮重新審視基礎知識並質疑你是否掌握了它們。 –

+0

轉換完全std :: string後,我發現我的問題不在這個類內,但在另一個位置。只是從char *轉換爲char []。似乎很奇怪,但再次工作。無論最後一條消息如何,我都會給你一個+。 –