2014-10-29 200 views
1

好的,下面是解釋它的簡單方法,下面的代碼來自於虛幻引擎3遊戲的SDK,因此大部分代碼都是由單獨的程序生成的,而不是由我自己生成的,但是我遇到了一個問題,我似乎無法解決它。C++內存泄漏問題

基本上,這是我打電話

if (Entity->GetHumanReadableName().Data) 

線的功能造成一個非常小的泄漏(在幾個小時內增加,直到程序崩潰),現在我使用的GetHumanReadableName功能只是爲了這個目的,但任何返回「FSTRING」的函數都會導致泄漏,這對我來說意味着我的FSTRING正在泄漏,但我無法弄清楚在哪裏。

所以我希望打破每一層,並希望你們可以弄清楚這與我?

struct FString AActor::GetHumanReadableName () 
{ 
    static UFunction* pFnGetHumanReadableName = NULL; 

    if (! pFnGetHumanReadableName) 
     pFnGetHumanReadableName = (UFunction*) UObject::GObjObjects()->Data[ 3859 ]; 

    AActor_execGetHumanReadableName_Parms GetHumanReadableName_Parms; 

    this->ProcessEvent (pFnGetHumanReadableName, &GetHumanReadableName_Parms, NULL); 

    return GetHumanReadableName_Parms.ReturnValue; 
}; 

一個fstring結構

struct FString : public TArray<wchar_t> 
{ 
    FString() {}; 

    FString (wchar_t* Other) 
    { 
     this->Max = this->Count = *Other ? (wcslen (Other) + 1) : 0; 

     if (this->Count) 
      this->Data = Other; 
    }; 

    ~FString() {}; 

    FString operator = (wchar_t* Other) 
    { 
     if (this->Data != Other) 
     { 
      this->Max = this->Count = *Other ? (wcslen (Other) + 1) : 0; 

      if (this->Count) 
       this->Data = Other; 
     } 

     return *this; 
    }; 
}; 

在tarray結構

template< class T > struct TArray 
{ 
public: 
    T* Data; 
    int Count; 
    int Max; 

public: 
    TArray() 
    { 
     Data = NULL; 
     Count = Max = 0; 
    }; 

public: 
    int Num() 
    { 
     return this->Count; 
    }; 

    T& operator() (int i) 
    { 
     return this->Data[ i ]; 
    }; 

    const T& operator() (int i) const 
    { 
     return this->Data[ i ]; 
    }; 

    void Add (T InputData) 
    { 
     Data = (T*) realloc (Data, sizeof (T) * (Count + 1)); 
     Data[ Count++ ] = InputData; 
     Max = Count; 
    }; 

    void Clear() 
    { 
     free (Data); 
     Count = Max = 0; 
    }; 
}; 

我的意思是,我敢肯定,我必須用在tarray或一個fstring的解構得一塌糊塗,但我只是不確定我需要做什麼...如果你需要更多的代碼提示,請讓我知道。

回答

3

當對象被銷燬時,需要調用free(Data)

TArray結構調用Clear()創建析構函數:

~TArray() { Clear(); } 

而且,你會想測試Data,以確保它是不是NULL之前free()它(並將其設置爲之後根據Rafael的評論,可獲得NULL)。所以在Clear()方法改變free()行:

if (Data != NULL) { 
    free(Data); 
    Data = NULL; // edit per Rafael Baptista 
} 
+1

同樣清晰,確保數據的自由後,設置爲NULL。否則,如果在清除後插入,則會崩潰。 – 2014-10-29 02:17:33

+0

ERR上保持1秒,在註釋格式沒有幫助洛爾 – Casper7526 2014-10-29 02:18:39

+0

公共: \t在tarray() \t { \t \t數據= NULL; \t \t Count = Max = 0; \t}; \t〜TArray(){Clear(); } – Casper7526 2014-10-29 02:19:57