Basic Segmentation Error - c++

I have run into an issue of the most simple kind that I cannot seem to resolve.
I have a class called UI, inside UI.h I am storing a single variable called index, and have a method setup(), which sets the value of index:
class UI {
public:
float index;
public:
void setup(float p_selectedMicrobeIndex);
};
With the implementation of setup being:
void UI::setup(float p_selectedMicrobeIndex)
{
microbeIndex = p_selectedMicrobeIndex;
}
Inside my game class .h file I am declaring an instance of a class called UI:
#include "UI.h"
class Game {
private:
UI* ui;
};
Inside Game.cpp I am running UI.setup() to set the value of index.
ui->setup(0.0f);
I am struggling to understand why this results in a segmentation error.
Any help would be appreciated. Thanks.

You are creating a pointer, but you don't create an instance for it to point to. You should either create an intance
UI ui;
ui.setup(0.0f);
or do so with a pointer (although I don't see why)
UI* ui = new UI;
ui->setup(0.0f);
such that the pointer actually points to something sensible.
UI* ui; just reserves memory for the pointer to an object of UI but no memory for the UI object. Thus, the setup fails, because you try to write to not allocated memory.

Related

Do I need to delete point in plugin class in Qt?

Now, I perfect my question.The pointer m_Core will be initialized and GetCore() will be called first for sure.The most I concerned is the document said root component will be deleted automatically when QPluginLoader is fully unloaded,and I don't know how Qt process the memory when Qt destruct QPluginloader and instances. If Qt will delete the Object before the destruction of QPluginLoader, I don't need to free it manually. In fact, when I invalid the delete m_Core, Qt reports no err, if I valid it, Qt will report segment fault, so Qt must destruct Mplugin class before call ~Mplugin() function.
The m_Core is derived class of QWidget:
SF_Core.h
#include <QWidget>
class SF_Core:public QWidget
{
SF_Core(QWidget* parent):QWidget(parent){}
~SF_Core(){}
};
and I use it through QPluginLoader in my project like this:
mainWindow.h
#include "MInterface.h"
#include "SF_Core.h"
#include <QWidget>
class MainWindow:public QWidget
{
Q_Object
MainWindow();
~MainWindow();
private:
MInterface* interface;
QObject* plugin;
MCore* core;
}
mainWindow.cpp
void mainWindow::mainWindow()
{
QPluginLoader loader("SF_Core.dll");
plugin = loader.instance();
interface = qobject_cast<MInterface* >(plugin);
core = interface->GetCore();
}
I have a plugin class derived from MIngerface class in Qt program, and override the function GetCore() in MIngerface.
#include "SF_Core.h"
class Mplugin:public QObject,MInterface
{
Q_OBJECT
Q_PLUGIN_METADATA(IID INTERFACE_ID)
Q_INTERFACES(MInterface)
public:
Mplugin();
~Mplugin(){
delete m_Core;
}
SF_Core* GetCore(){
m_Core = new SF_Core;
return m_Core;
}
private:
SF_Core* m_Core;
};
In main program, I load the plugin by QPluginLoader,and use instance() to get the root component. When I terminated the program, it crashed.I found the err came from the sentence delete m_Core; If I don't delete m_Core, will it cause memory leak?
Initial short answer
Keeping in mind the principle of ownership, most probably yes: it will cause memory leak.
Also, consider that each call to GetCore will allocate a new instance and create memory leak.
However, without having a full example, it is difficult to understand how SF_Core is used, especially if it ownership is transferred or not.
Stack variable fix
What if you use an internal stack value? (Not the best practice, however to publish internal properties)
SF_Core* GetCore()
{
return &m_Core;
}
private:
SF_Core m_Core;
Alternative using shared_ptr
An alternative is to use smart pointer (which I highly recommend over raw pointers whenever possible):
using SfCorePtr = std::shared_ptr<SF_Core>;
SfCorePtr GetCore()
{
if (!m_CorePtr)
{
m_CorePtr = std::make_shared<SF_Core>(); // Lazy creation
}
return m_CorePtr;
}
private:
SfCorePtr m_Core;
Hint: to be even more pedantic, the use of std::weak_ptr allows to give access to a smart pointer without providing it ownership: If GetCore return a weak_ptr, the ownership of m_Core is keep inside this object and the ownership stay in a tree-shape instead of graph-shape.
Minimal fix
Otherwise, just fixing your code:
#include "Mcore.h"
class Mplugin:public QObject,MInterface
{
Q_OBJECT
Q_PLUGIN_METADATA(IID INTERFACE_ID)
Q_INTERFACES(MInterface)
public:
Mplugin();
virtual ~Mplugin(){
delete m_Core;
}
SF_Core* GetCore(){
if (nullptr == m_Core){
m_Core = new SF_Core;
}
return m_Core;
}
private:
SF_Core* m_Core=nullptr;
};

How the creation of objects on the stack in Qt "function / method" work?

For example, I have code that I often see:
class SomeClass : public QObject
{
Q_OBJECT
public:
QHash *parameterTable;
explicit ExCurrentSession(QObject *parent = nullptr);
};
SomeClass::SomeClass(QObject *parent) : QObject(parent)
{
parameterTable = new QHash;//used dynamic creation
QFile file("someFile.txt");//Creating an object on the stack
if (!file.open(QIODevice::ReadOnly|QIODevice::WriteOnly))
QTextStream fileSream(&file);//Creating an object on the stack
QString buff = fileSream.readLine();//Creating an object on the stack
//...Other code to set the QHash table with a parameter and a value from a file...
}
The question is whether there will be memory leaks after exiting the method:
-QFile file ? I have no idea what's inside there using dynamic memory, maybe it's not used there.And if it`s using in another subclass inside this class.
-QTextStream fileSream ?I have no idea what's inside object using dynamic memory or not, maybe it's not used there.And if it`s using in another subclass inside this class.
-QString buff?I have no idea what's inside object using dynamic memory or not, maybe it's not used there.
I don’t understand how to determine whether it is possible to use an object on a stack (method / function) if you did not write it yourself and do not 100% sure that dynamic memory allocation is not used there.
Maybe it is more correct? But why often write as in the first version.
SomeClass::SomeClass(QObject *parent) : QObject(parent)
{
parameterTable = new QHash;//used dynamic creation
QFile *file = new QFile("someFile.txt");//Creating an object on the stack
if (!file->open(QIODevice::ReadOnly|QIODevice::WriteOnly))
QTextStream *fileSream = new QTextStream(file);//Creating an object on the stack
QString *buff = fileSream->readLine();//Creating an object on the stack
//...Other code to set the QHash table with a parameter and a value from a file...
delete file;
delete fileSream;
delete buff;
}
For "someHash" the destructor is invoked automatically as well?
class SomeClass : public QObject
{
Q_OBJECT
public:
QHash<QString,QString> someHash;
};

When should I use pointer or reference members, and when should I pass nullptr or this as parent pointer in Qt?

The Code
I've been writing this c++ with Qt knowing it works but not really understanding why I sometimes do things other than "I just know I should be doing this".
This is my startup class which initialises my classes:
namespace GUI
{
Startup::Startup() :
QObject(nullptr),
m_setupTab(*new SetupTab(nullptr)),
m_regTab(*new CbcRegistersTab(nullptr)),
m_dataTab(*new DataTestTab(nullptr)),
m_mainView(*new MainView(nullptr,
m_setupTab,
m_regTab,
m_dataTab)),
m_systemController(*new SystemController(nullptr,
Provider::getSettingsAsSingleton())),
m_dataTest(*new DataTest(nullptr,
m_systemController)),
m_setupTabVm(new SetupTabViewManager(this,
m_setupTab,
m_systemController,
Provider::getSettingsAsSingleton() ))
{
}
Then in my header file the member variables are described as such:
private:
SetupTab& m_setupTab;
CbcRegistersTab& m_regTab;
DataTestTab& m_dataTab;
MainView& m_mainView;
Settings* m_settings;
SystemController& m_systemController;
DataTest& m_dataTest;
SetupTabViewManager* m_setupTabVm;
The main difference between the view manager and everything else is that view manager passes signals between the tab classes and everything else.
Then to start this in my main, all I do is this:
GUI::Startup startup;
startup.show();
SetupTabViewManager.cpp:
#include "setuptabviewmanager.h"
#include "View/setuptab.h"
#include "Model/systemcontroller.h"
#include "Model/settings.h"
#include <QDebug>
namespace GUI
{
SetupTabViewManager::SetupTabViewManager(QObject *parent,
SetupTab& tab,
SystemController& sysCtrl,
Settings& config) :
QObject(parent),
m_setupTab(tab),
m_systemController(sysCtrl)
{
WireMessages(config);
WireSetupTabButtons(config);
}
void SetupTabViewManager::WireMessages(Settings& config)
{
connect(&config, SIGNAL(notifyStatusMessage(QString)), //for QT4
&m_setupTab, SLOT(onStatusUpdate(QString)) );
connect(&m_systemController, SIGNAL(notifyStatusMessage(QString)),
&m_setupTab, SLOT(onStatusUpdate(QString)));
}
void SetupTabViewManager::WireSetupTabButtons(Settings& config)
{
connect(&m_setupTab, SIGNAL(onBtnLoadSettingsClicked(bool)),
&config, SLOT(onLoadButtonClicked(bool)) );
connect(&config, SIGNAL(setHwTree(QStandardItemModel*)),
&m_setupTab, SLOT(setHwTreeView(QStandardItemModel*)));
connect(&m_setupTab, SIGNAL(onBtnInitClicked()),
&m_systemController, SLOT(startInitialiseHw()));
connect(&m_setupTab, SIGNAL(onBtnCfgClicked()),
&m_systemController, SLOT(startConfigureHw()));
}
}
Questions
What is the advantage of initialising a class in a member variable as a pointer or a reference? I just know when I make a "view manager", I should initialise the member variable as a pointer. Though I'm not sure why?
Also what is the advantage of "this" or "nullptr" as the parent to the class?
Qt objects are organized in object trees. It allows a programmer not to care about destructing the created objects: they will be deleted automatically when their respective parents are deleted.
If you take a look at almost any Qt GUI application, then you will see that all of its widgets (buttons, checkboxes, panels, etc.) have one single ancestor - the main window. When you delete the main window, all your application widgets are automatically deleted.
You can set up this parent-child relation by passing a parent object to a newly created child:
QWidget *mainWidget = ...
QPushButton *btn = new QPushButton(mainWidget);
In this case, btn object becomes a child of the mainWidget object, and from this moment you may not delete that child manually.
If you create an object without a parent, you should always delete it by yourself.
As thuga mentioned in the comments, you can transfer object ownership later. Widgets can be places inside layouts and it will make them children of the layout owner. Or you can even explicitly set parent with QObject::setParent.
And as for declaring class members as pointers or references - it does not really matter. It's just a question of convenience.
In Qt world all child objects are getting deleted when their parent object is deleting. If you do not define class members (QObjects) as pointers, they will be deleted twice: once by their parent, and second time when your class object is destructed by itself, and this can lead to undefined behavior.

Public member not initialized

I am making a client server application, with the server having a GUI. I am using Qt.
For communication I am using pipes.
I have divided the server application into a backend, and a GUI. The backend has a PipeServer class, and in the GUI, I have overriden functions like onReceiveMessage etc.
Everything worked fine until I decided to add a std::queue as a base class member.
At the start of the application, I get an exception, and upon inspection it seems that my queue does not start with 0 elements. In fact it seems like the queue is not initialized at all. There are 2 possibilites: it could be because I the GUI class inherits 2 classes, and somehow the second base class, which is my PipeServer does not properly initialize its members, or it could be because the pipeServerGUI object is moved to a different thread by QT.
Any ideas on how I could solve this?
Relevant code:
class HookServer
{
PIPEINST Pipe[INSTANCES];
HANDLE hEvents[INSTANCES];
VOID DisconnectAndReconnect(DWORD);
BOOL ConnectToNewClient(HANDLE, LPOVERLAPPED);
VOID GetAnswerToRequest(LPPIPEINST);
public:
std::queue<std::string> messages;
int init(std::string pipename);
int run();
virtual void onNewConnection() {};
virtual void onReceiveMessage(std::string message) {};
};
class HookServerGUI : public QObject, public HookServer
{
Q_OBJECT
void onReceiveMessage(std::string message);
void onNewConnection();
public slots:
void doWork() {
init("\\\\.\\pipe\\hookpipe");
run();
}
signals:
void signalGUI(QString message);
};
//GUIServerCreation
QThread *thread = new QThread;
HookServerGUI* worker = new HookServerGUI;
QObject::connect(worker,SIGNAL(signalGUI(const QString&)),this,SLOT(processMessage(const QString&)));
worker->moveToThread(thread);
thread->start();
QMetaObject::invokeMethod(worker, "doWork", Qt::QueuedConnection);
EDIT:
The exception is a access violation exception. It happens in this part of code:
VOID HookServer::GetAnswerToRequest(LPPIPEINST pipe)
{
onReceiveMessage(pipe->chRequest);
if(!messages.empty())
{
std::string s = messages.front();
messages.pop();
strcpy(pipe->chReply,s.c_str());
pipe->cbToWrite = strlen(s.c_str()+1);
}
}
Since messages.empty() return some huge number, it tries to read the first object and somehow fails.
There is also no PipeServerGUI constructor.
EDIT2:
I solved part of this problem by placing parenthesis after new HookServerGUI();
The problem is that still the function does not work, and throws a access violation exception. It happens on the front() line. When checked in a debugger, the function does have 1 element, so it is not because it is empty. Any ideas?
EDIT3:
With the second run, unfortunately the queue.size() is still incorrect. Seems like a data race to me.
The problems are in the code that you don't show, and it's a classic case of a memory bug, it looks like. Some code somewhere is writing on memory it doesn't own. Probably you have a bug in the way you use winapi. You need to create a minimal, self-contained test case.
I think you might be shooting yourself in the foot by not using QLocalSocket: on Windows, it's a named pipe - exactly what you want.
Besides, this is C++ code. There is no reason at all to put either PIPEINST or HANDLE into a raw C array. Use QVector or std::vector. Probably the rest of the code is full of C-isms like that, and something somewhere goes wrong.
I wouldn't discount a buffer overrun, since obviously you are ignoring the size of the buffer in PIPEINST from the - the strcpy can overrun the buffer. I'm also not sure that PIPEINST from the example code is using the same character type as what std::string::c_str() is returning.
Even if you wanted to implement your code using explicit pipes without QLocalSocket, you should still use C++, QString etc. and understand what's going on with your data.

Qt - Open single instance of a window

How do I check if a window/dialog is already open? I used this code to open a new dialog box but everytime I click it the dialog keeps on opening. Obviously not the way settings dialog works.
Class *someClass = new Class();
someclass->show();
In your code you create a new window/widget/dialog everytime.
Initialize *someClass somewhere else and then only show it.
class Foo
{
public:
Foo() { someClass = new SomeClass() }
void fooClicked() { someClass->show() }
private:
SomeClass *someClass;
};
In your calling class (or main application class, or something similar) define a pointer to the class:
dialogclass *someclass;
In the constructor of that main class, initialize the dialog class:
someclass = NULL;
When you want to show the dialog, do something along these lines:
if (!someclass) someclass = new dialogclass(); // Creates a dialog instance if it does not already exist
if (!someclass->isVisible()) someclass->show(); // Only shows the dialog if it is not already shown.
Use QPointer:
QPointer<MyDialog> dialog = new MyDialog(this);
dialog->show();
...
if (dialog) dialog->show();
If dialog exists it will be shown. If it is deleted in the meantime, it will hold 0 instead of an invalid address, and the last line will never be executed - it will not be shown but you can recreate it if needed.
You can make an static pointer on your window class. It allows you to store last opened window object.
class MyWindow : public QWidget {
public :
static MyWindow* instance;
...
}
Whenever you make a new instance you can set instance. When the instance is null you can make a new window. When you want to close the opened window, you should make instance null again. This allows you to have only one open window.
if (MyWindow::instance == NULL) {
MyWindow *w = new MyWindow(...);
MyWindow::instance = w;
}
This design pattern is called Singleton and it allows you to have only one object per a class. Also, this is a bit different because in Singleton, constructor is not public and factory method should be used for making an object but it is similar.