I tried to have a dynamic memory allocation inside my application. If I try to allocate memroy in OnInit()
then the application crashes.
Currently I'm using the lastest stable version of wxWidgets 3.0.4 with Visual Studio 2010.
If I comment #define BUFFER
the application works as expected.
my 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);
}
With
buffer0 = new int(1000);
you allocate memory for 1 (in words: one) int
and initialize it with 10000
. Then with
memset(buffer0, 0, 10 * sizeof(int));
you set 10 * sizeof(int)
bytes starting at buffer
to zero. You access memory that isn't yours.
Since you use delete[]
in your destructor I guess you wanted to write
buffer0 = new int[1000];
or even
buffer0 = new int[1000]{};
to initialize the int
s with zero without having to use memset()
.
Use
std::vector<int> buffer0(1000);