【问题标题】:C++ Memory Leak IssuesC++ 内存泄漏问题
【发布时间】:2014-10-29 02:10:05
【问题描述】:

好的,这里是简单的解释方法,以下代码来自虚幻引擎 3 游戏的 SDK,所以显示的大部分代码是由单独的程序生成的,而不是我自己生成的,但是我已经运行遇到问题,我似乎无法解决。

基本上,这就是我要调用的行

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 的解构器,但我只是不确定我需要做什么...如果您需要更多代码摘录,请告诉我。

【问题讨论】:

    标签: c++ memory-leaks


    【解决方案1】:

    对象被销毁时需要调用free( Data )

    在您的 TArray 结构中创建一个调用 Clear() 的析构函数:

    ~TArray() { Clear(); }
    

    此外,您将要测试 Data 以确保它在 free() 之前不是 NULL(然后根据 Rafael 的评论将其设置为 NULL)。所以在Clear() 方法中将free() 行更改为:

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

    【讨论】:

    • 同样明确,释放后一定要设置Data为NULL。否则如果你在清除后插入,你会崩溃。
    • public: TArray() { Data = NULL;计数 = 最大值 = 0; }; ~TArray() { 清除(); }
    • 解构器的正确位置对吗?
    • 是的,把它放在构造函数之后很常见。
    • 感谢您的帮助,将测试:)
    猜你喜欢
    • 2011-05-16
    • 1970-01-01
    • 2022-11-10
    • 2010-12-15
    • 2011-07-29
    • 1970-01-01
    • 2016-07-28
    相关资源
    最近更新 更多