Visual C ++内存泄漏

时间:2017-07-27 16:07:55

标签: windows visual-studio visual-c++ c++-cli managed-c++

我有一个我正在创建的串行通信库,它是一个托管程序集,它带有它自己的规则(我不完全理解它们,我只是在VS抱怨时更改代码),而且我有我无法弄清楚的内存泄漏。

这是我得到的泄漏警告(第11行是SerialComm :: SerialComm()中的InfoContainer构造函数):

Detected memory leaks!
Dumping objects ->
SerialComm.cpp(11) : {144} normal block at 0x011468B8, 56 bytes long.
Data: <                > 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
Object dump complete.

这是lib的.h文件:

#include <windows.h>
#include <stdlib.h>
#include <atlstr.h>

public class InfoContainer {
public:
    ~InfoContainer();
    HANDLE handle;
    bool connected;
    COMSTAT status;
    DWORD errors;
    DCB connection_params;
    CStringA port_name;
};

public ref class SerialComm {
public:
    InfoContainer* info=0;
    SerialComm();
    ~SerialComm();
    bool OpenConnection(String^ Portname);
    int CloseConnection();
    bool WriteData(String^ toSend);
    String^ ReadData(int bytesToRead);
};

这些是相关的.cpp部分:

SerialComm::SerialComm() {
    info = new (_NORMAL_BLOCK, __FILE__, __LINE__) InfoContainer();
    info->handle = 0;
}
SerialComm::~SerialComm() {
    CloseConnection();
    delete info;
}

bool SerialComm::OpenConnection(String ^ Portname) {
    info->port_name = Portname;

    //visual studio's valgrindish tool
    _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
    _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDOUT);
    _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
    _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDOUT);
    _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
    _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDOUT);
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
    _CrtDumpMemoryLeaks();


    info->handle = CreateFileA(
        info->port_name,
        GENERIC_READ | GENERIC_WRITE,
        0,
        NULL,
        OPEN_EXISTING,
        0,
        NULL

    );
    if (info->handle == INVALID_HANDLE_VALUE) {
        ATLTRACE("Error: %d", GetLastError());
        printf("Error: %d\n", GetLastError());
        return false;
    }
    //
    //rest of connection code here
    //
}

int SerialComm::CloseConnection() {
    return CloseHandle(info->handle);
}

InfoContainer::~InfoContainer() {
    delete handle;
}

我必须在主类中使用InfoContainer类和InfoContainer指针的原因是我需要存储的一些信息被认为是非托管代码,所以我不能直接在主类中使用它。

提前致谢!

1 个答案:

答案 0 :(得分:0)

问题是在删除所有对象之前调用_CrtDumpMemoryLeaks()

您需要终结器。在C ++ / CLI中编写类时,以下是“黄金模式”:

virtual ~SerialComm()
{
    this->!SerialComm();
}

!SerialComm()
{
}

不要忘记将虚拟添加到析构函数中。需要虚拟析构函数的原因应该在任何优秀的C ++教科书中解释。

相关问题