C++ 内存泄漏问题

标签 c++ memory-leaks

好的,下面是解释它的简单方法,以下代码来自虚幻引擎 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; 
    }; 
}; 

塔瑞结构

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

最佳答案

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

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

~TArray() { Clear(); }

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

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

关于C++ 内存泄漏问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26621700/

相关文章:

c++ - 在哪里可以找到当前的 C 或 C++ 标准文档?

c++ - execv 会在前台还是后台运行它?

c++ - 什么是 "one-stop memory corruption"?

android - 如何在 Android 中查找内存泄漏类/Activity

c - 神秘变化的结构成员(涉及指针):

c++ - 异步I/O回调方法并发

c++ - 如何在参数和返回类型上使用匹配的 const 修饰符编写函数?

c++ - 我可以在 main() 函数之外使用 GetAsyncKeyState() 吗?

c++ - std::bad_alloc 运行时异常

iphone - 使用 RGB 方法的 UICOLOR 颜色中的内存泄漏