内存分配wxWidgets

memory alllocation wxWidgets

我试图在我的应用程序中进行动态内存分配。如果我尝试在 OnInit() 中分配内存,那么应用程序会崩溃。

目前我使用的是 Visual Studio 2010 的最新稳定版 wxWidgets 3.0.4。

如果我评论 #define BUFFER 应用程序会按预期工作。

我的main.h:

#include <wx/wx.h>

class MyApp : public wxApp {
    public:
        virtual bool OnInit();
};

class MainWindow : public wxFrame {
    public:
        MainWindow(const wxPoint& position, const wxSize& size);
        ~MainWindow();

    private:
        void setupUi();

        int *buffer0;
};

main.cpp

#include "main.h"

#define BUFFER
IMPLEMENT_APP(MyApp)

//-----------------------------------------------------------------------------
bool MyApp::OnInit() {
    MainWindow *main = new MainWindow(wxPoint(20, 20), wxSize(300, 200));
    main->Show(true);

    return true;
}


//----------------------------------------------------------------------------
MainWindow::MainWindow(const wxPoint& position, const wxSize& size) : wxFrame(NULL, wxID_ANY, "Frame") {
    setupUi();
#ifdef BUFFER
    buffer0 = new int(1000);
    memset(buffer0, 0, 10 * sizeof(int));
#endif
}


//----------------------------------------------------------------------------
MainWindow::~MainWindow() {
#ifdef BUFFER
    delete[] buffer0;
#endif
}

//----------------------------------------------------------------------------
void MainWindow::setupUi() {
    wxBoxSizer *bsMain = new wxBoxSizer(wxVERTICAL);
    wxStaticBox *sbInfo = new wxStaticBox(this, wxID_ANY, "INFORMATION");

    bsMain->Add(sbInfo, 1, wxALL | wxEXPAND, 15);
    SetSizer(bsMain);
}

有区别

buffer0 = new int(1000); // allocate sizeof(int) bytes

buffer0 = new int[1000]; // allocate sizeof(int) * 1000 bytes

你的程序有未定义的行为,因为你分配了 sizeof(int) 字节但是

memset(buffer0, 0, 10 * sizeof(int));

您想将 sizeof(int) * 10 字节设置为 0。您正在访问您无权访问的内存。 使用方括号创建数组 new int[1000].

buffer0 = new int(1000);

您为 1(换句话说:一个)int 分配内存并用 10000 初始化它。然后用

memset(buffer0, 0, 10 * sizeof(int));

您将 buffer 开始的 10 * sizeof(int) 个字节设置为零。你访问了不属于你的记忆。

因为你在析构函数中使用了 delete[] 我猜你想写

buffer0 = new int[1000];

甚至

buffer0 = new int[1000]{};

用零初始化 int,而不必使用 memset()


真实(tm)答案:

使用

std::vector<int> buffer0(1000);