C++ program is crashing on constructor - c++

I have strange crash on my program. I run the program in a Linux environment.
This is the code:
class classB
{
public:
classB(classA* pi_pCreator)
{
m_pCreator = pi_pCreator;
}
bool DoAction()
{
if(m_pCreator)
{
//do some code
return true;
}
return false;
}
private:
classA* m_pCreator = NULL;
};
void Correlate(classA* pi_pCreator)
{
classB l_oCorrelate(pi_pCreator);
bool res = l_oCorrelate.DoAction();
if (res)
{
return;
}
else
{
pi_pCreator->DoErrorAction();
}
}
I am using crashfind to find the source of the crash and result is referring to this line:
classB l_oCorrelate(pi_pCreator);
Usually the function Correlate is called with a valid pi_pCreator, but also there are some cases with NULL.
Is the constructor of classB is really the problem, or is dereferencing the problem?

Related

Why is my code getting a segmentation error

For the life of me I cannot understand at all why this program is getting a segmentation error. The issue is that it retrieves an object within the vector container uses a function within the menu class using the get_command() and for some reason after testing the main function line by line this one results in a segmentation fault:
menu->get_command()->execute();
I have tried changing the syntax to create a new command object that stores the returned object from get_command() and changed the index between 0 and -1 and still nothing fixes the error. I have spent at least a couple of hours trying to figure out why but I cannot seem to find a solution.
class Base {
public:
/* Constructors */
Base() { };
/* Pure Virtual Functions */
virtual double evaluate() = 0;
virtual std::string stringify() = 0;
};
class op : public Base
{
public:
op() { };
op(double op1) { operand = op1; }
double evaluate() { return operand; }
string stringify() {
string value = to_string(operand);
return value;
}
private:
double operand;
};
class Command {
protected:
Base* root;
public:
Command() { this->root = nullptr; }
double execute() { return root->evaluate(); }
std::string stringify() { return root->stringify(); }
Base* get_root() { return root; }
};
class Menu {
private:
int history_index; // Indexes which command was last executed, accounting for undo and redo functions
std::vector<Command*> history; // Holds all the commands that have been executed until now
public:
Menu() {
// Constructor which initializes the internal members
history_index = -1;
}
std::string execute() {
// Returns the string converted evaluation of the current command
return to_string(history[history_index - 1]->execute());
}
std::string stringify() {
// Returns the stringified version of the current command
return history[history_index]->stringify();
}
bool initialized() {
// Returns if the history has an InitialCommand, which is necessary to start the calculation
if (history[history_index] != nullptr)
return true;
else
return false;
}
void add_command(Command* cmd) {
// Adds a command to the history (does not execute it), this may require removal of some other commands depending on where history_index is
history.push_back(cmd);
history_index++;
}
Command* get_command() {
// Returns the command that the history_index is currently referring to
return history[history_index];
}
void undo() {
// Move back one command (does not execute it) if there is a command to undo
history_index--;
}
void redo() {
// Moves forward one command (does not execute it) if there is a command to redo
history_index++;
}
};
class InitialCommand : public Command {
protected:
Base* root;
public:
InitialCommand(Base* b) { this->root = b; }
double execute() { return root->evaluate(); }
std::string stringify() { return root->stringify(); }
Base* get_root() { return root; }
};
void main()
{
Menu* menu = new Menu();
InitialCommand* temp = new InitialCommand(new op(7));
menu->add_command(temp);
EXPECT_EQ(menu->get_command()->execute(), 7);
system("PAUSE");
}
You're not doing inheritance right, as you are duplicating fields between Command and InitialCommand that lead to the error.
Both command classes have a Base *root member, and non-virtual execute methods. When you construct a new InitialCommand object, the InitialCommand::root object points at the op that was created for it, while Command::root remains NULL because of the default constructor for Command. Then, when you call menu->get_command(), it will call Command::execute because execute is non-virtual and menu is a Command *. Command::execute will then dereference a NULL root, causing your segmentation error.
Remove the Base *root member from InitialCommand, and pass the parameter to a constructor in Command. You probably want to make some methods like execute virtual.
The problem is that your Command and InitialCommand both have root variable.
InitialCommand* temp = new InitialCommand(new op(7)); will according to your constructor set InitialCommand::root. So Command::root remains uninitialized. Then Menu holds std::vector<Command*>, so InitialCommand* is implicitly converted to Command*.
At alst calling Command::execute will indeed call Command:execute because the method is not virtual. So, the uninitialized Command::root is used -> seg. fault.
Please don't use new. Use smart pointers - std::unique_ptr should be the default way to manage dynamic memory.
That said, your code seems too Java/C# like. This is C++, use value semantics if you can. There's no reason for Menu* menu = new Menu();. Menu menu; is simpler and works the same in your case. Here's a code I would've written
#include <memory>
#include <vector>
#include <string>
using namespace std;//Not a good practice and definitely a big no in header files.
class Base {
public:
/* Constructors */
Base() { };
/* Pure Virtual Functions */
virtual double evaluate() = 0;
virtual std::string stringify() = 0;
};
class op : public Base
{
public:
op() { };
op(double op1) { operand = op1; }
double evaluate() { return operand; }
string stringify() {
string value = to_string(operand);
return value;
}
private:
double operand;
};
class Command {
protected:
std::unique_ptr<Base> root;
public:
Command(std::unique_ptr<Base>&& root):root(std::move(root)) { }
//Be const-correct
double execute() const { return root->evaluate(); }
std::string stringify() const { return root->stringify(); }
Base* get_root() const { return root.get(); }
};
class Menu {
private:
int history_index; // Indexes which command was last executed, accounting for undo and redo functions
std::vector<std::unique_ptr<Command>> history; // Holds all the commands that have been executed until now
public:
Menu() {
// Constructor which initializes the internal members
history_index = -1;
}
std::string execute() const{
// Returns the string converted evaluation of the current command
return to_string(history[history_index - 1]->execute());
}
std::string stringify() const{
// Returns the stringified version of the current command
return history[history_index]->stringify();
}
bool initialized() const{
// Returns if the history has an InitialCommand, which is necessary to start the calculation
if (history[history_index] != nullptr)
return true;
else
return false;
}
void add_command(std::unique_ptr<Command>&& cmd) {
// Adds a command to the history (does not execute it), this may require removal of some other commands depending on where history_index is
history.emplace_back(std::move(cmd));
history_index++;
}
Command* get_command() const {
// Returns the command that the history_index is currently referring to
return history[history_index].get();
}
void undo() {
// Move back one command (does not execute it) if there is a command to undo
history_index--;
}
void redo() {
// Moves forward one command (does not execute it) if there is a command to redo
history_index++;
}
};
class InitialCommand : public Command {
protected:
public:
InitialCommand(std::unique_ptr<Base>&& b): Command(std::move(b)){}
};
// There's no such thing as void main
int main()
{
Menu menu;
auto temp = std::make_unique<InitialCommand>(std::make_unique<op>(7));
menu.add_command(std::move(temp));
//EXPECT_EQ(menu.get_command()->execute(), 7);
system("PAUSE");
}
It uses move semantics which used to not be a beginners concept, but it's such integral part of modern C++ that every C++ programmer must learn it sooner rather than later.

Passing data by reference to build it

Under C++ I usually ran into an error.
Suppose I have the following classes:
class ClassData
{
public:
ClassData() { a=-1; }
public:
int a;
};
class MyClass
{
public:
MyClass() { m_classData = 0; }
MyClass(ClassData* classData) { m_classData = new ClassData(*classData); m_classData->a=1; }
inline bool getClassData(ClassData* classData) {
if (m_classData) { classData = m_classData; return true; }
else return false;
}
private:
ClassData* m_classData;
};
Now in the main I run this test code:
ClassData cdata;
MyClass* m_myClass = new MyClass(&cdata);
int value = 0;
ClassData classData;
if (m_myClass->getClassData(&classData))
value = classData.a;
If the code is run, value is equal to -1 (instead of 1).
First question: why I've not been able to take a reference to ClassData in MyClass? While I'm thinking to have the ClassData object of m_myClass (like doing m_myClass->m_classData if it would be public), in reality I'm calling the member a on local ClassData object.
I was thinking that the cause was that I cannot change the local variable address, but if I change the code into this:
ClassData* classData=0;
if (m_myClass->getClassData(classData))
value = classData->a;
I get my program crashing.
Second question: what is the correct way to manage this situation? Is the issue located in the program main function or in how getClassData is defined giving room for mistakes?
Here:
bool getClassData(ClassData* classData) {
if (m_classData) { classData = m_classData; return true; }
else return false;
}
Notice that classData is a local variable. It dies when the function terminates, so the function really does nothing except report whether its m_classData is null or not.
So in the first case:
ClassData classData; // <-- classData.a is -1
if (m_myClass->getClassData(&classData))
value = classData.a; // <-- classData.a is still -1
In the second case:
ClassData* classData=0; // classData is null
if (m_myClass->getClassData(classData))
value = classData->a; // classData is still null
you dereference a null pointer, which is Undefined Behavior. You're lucky all it does is crash.
A correct (but still unsafe) way to do it is like this:
bool getClassData(ClassData* classData) {
if (m_classData!=0 && classData!=0)
{ classData->a = m_classData->a; return true; }
else return false;
}
I say "still unsafe" because this function cannot really verify that these pointers point to valid data structures. To avoid this danger you must refrain from using pointers so much, and look into references.
Using values instead of pointers simplifies things and will also remove your memory leak. See live example
#include <iostream>
class ClassData
{
public:
ClassData() { a=-1; }
public:
int a;
};
class MyClass
{
public:
MyClass() { }
explicit
MyClass(ClassData const& classData) {
m_classData = classData;
m_classData.a=1;
}
ClassData const& getClassData() const {
return m_classData;
}
private:
ClassData m_classData;
};
int main()
{
ClassData classData;
MyClass myClass( classData );
classData = myClass.getClassData();
int value = classData.a;
std::cout << value;
}

After member function delete the current instance

After member function delete the current instance,how to stop the behind code executes.
See the code.
#include <iostream>
class A;
void callfun(int i,A *pt);
class A {
public:
A() { sss="this is A."; }
virtual ~A() {}
void foo(int i) {
callfun(i,this);  //call a function.Don't return value.Maybe delete instance.
out();       
}
private:
void out() {
std::cout<< "Out:" <<std::endl;
std::cout<< sss << std::endl;
}
std::string sss;
}
void callfun(int i,A *pt) {
if (i==0)
delete pt; //If conditions are matched,delete instance.
}
int main() {
A *a1=new A;
a1->foo(1); //print:Out:this is A.
a1->foo(0); //delete a1,don't print.But in fact it would print.how to do?
}
I want the result:foo(1) output "Out:this is A.",foo(0) delete instance,don't output.
Disclaimer: this is bad. bad. Terrible.
void foo(int i) {
if ( i == 1)
{
callfun(i,this);  //call a function.Don't return value.Maybe delete instance.
out();       
}
else
{
delete this;
}
}
Note that after you've done delete this; (cases where this is actually needed are rare) it's illegal to call any non-static functions on your instance, access the pointer (both inside or outside the method) or access any data members.
This is impossible, given the comments which state that foo shouldn't be aware of the deletion. That itself make the very next line Undefined Behavior. If callfun calls delete this, then foo MUST return immediately without even looking at this. Therefore you can't even set a "deleted" flag in this.
The closest I get is
void callfun(int i, A *pt) {
if (i==0) {
delete pt;
throw 0;
}
}
void A::foo(int i) {
try {
callfun(i,this);  // No _visible_ return value.
out();       
} catch (int) { }
}
If you delete internally, how does the enclosing scope know that its been deleted? You should just mark it and leave it up to the user/enclosing scope to actually dispose it.
The following is a more complete code.
class A;
class B {
public:
  void creat() {
pp=new A;
}
void remove() {
delete pp;
pp=NULL;
}
private:
A *pp;
};
class A {
public:
void foo(int i) {
callfun(i,this); 
    if (flag)
out();      
else
bb->remove();
}
private:
B *bb;
};

How come a pointer to a derived class cannot be passed to a function expecting a reference to a pointer to the base class?

Sorry for the long title but I did want to be specific.
I expected the following code to work but it doesn't and I can't figure out why :/
#include <cstdio>
#include <cassert>
class UniquePointer
{
public:
void Dispose()
{
delete this;
}
friend void SafeDispose(UniquePointer*& p)
{
if (p != NULL)
{
p->Dispose();
p = NULL;
}
}
protected:
UniquePointer() { }
UniquePointer(const UniquePointer&) { }
virtual ~UniquePointer() { }
};
class Building : public UniquePointer
{
public:
Building()
: mType(0)
{}
void SetBuildingType(int type) { mType = type; }
int GetBuildingType() const { return mType; }
protected:
virtual ~Building() { }
int mType;
};
void Foo()
{
Building* b = new Building();
b->SetBuildingType(5);
int a = b->GetBuildingType();
SafeDispose(b); // error C2664: 'SafeDispose' : cannot convert parameter 1 from 'Building *' to 'UniquePointer *&'
b->Dispose();
}
int main(int argc, char* argv[])
{
Foo();
return 0;
}
Imagine it were legal. Then you could write code like this:
class Animal : public UniquePointer
{
};
void Transmogrify(UniquePointer*& p)
{
p = new Animal();
}
void Foo()
{
Building* b = nullptr;
Transmogrify(b);
b->SetBuildingType(0); // crash
}
Observe that you have violated the type system (you put an Animal where a Building should be) without requiring a cast or raising a compiler error.
I do not think that it is possible to make it work the way you have it designed. Instead, try the following:
template <typename T>
void SafeDispose(T * & p)
{
if (p != NULL)
{
p->Dispose();
p = NULL;
}
}
class UniquePointer
{
public:
void Dispose()
{
delete this;
}
protected:
UniquePointer() { }
UniquePointer(const UniquePointer&) { }
virtual ~UniquePointer() { }
};
It is not allowed because if it were you could do the following:
friend void SafeDispose(UniquePointer*& p)
{
p = new UniquePointer();
}
Building* building;
SafeDispose(building)
//building points to a UniquePointer not a Building.
I guess the work around would be a template function.
To answer the title of your question, you cannot bind a non-const reference to base to a derived class instance because you could then set that reference to a pointer to a base instance that isn't a derived. Consider this function:
void Renew(UniquePointer *& p) {
delete p;
p = new UniquePointer();
}
if you could pass it a pointer to Building you would be able to set it incorrectly to point to a UniquePointer instance.
As it has already been suggested the solution is to change your reference to a plain pointer. Not only this solves your problem, but it is also a better implementation of SafeDispose(); as you wrote it this function gave the false idea that you would always set to 0 all your UniquePointer instances. But what would happen if somebody wrote (assuming UniquePointer constructor was public for simplicity):
UniquePointer *p1 = new UniquePointer();
UniquePointer *p2 = p1;
SafeDispose(p1);
They would expect all of their UniquePointers to be properly taken care of, when p2 is actually invalid.
I guess your SafeDispose should probably look more like :
friend void SafeDispose(UniquePointer** p) ...
In order to invoke it using
SafeDispose(&(UniquePointer*)b);
Then it should work this way.
But your next statement
b->Dispose();
will break cause b should now be NULL, cause it has been disposed and set to NULL by your SafeDispose method.

Unhandled Exception due to Class slicing

I'm getting an unhandled exception reading location 0x00000008 (reading NULL value) on the noted line below, relevant methods leading up to the error are included (continued below examples):
Event Methods:
Event::Event(Event::EVENTTYPE type) : eventType(type) { }
KeyEvent Methods:
class KeyboardKeyEvent : public Event {
public:
//...
int GetKey() const;
protected:
//...
};
int KeyboardKeyEvent::GetKey() const {
return this->_scancode; //Errors out here. "this" returns 0x000000
}
KeyboardKeyEvent::KeyboardKeyEvent(int key, Event::EVENTTYPE type) : Event(type), _scancode(key) { }
KeyDownEvent Methods:
KeyboardKeyDownEvent::KeyboardKeyDownEvent(int scancode) : KeyboardKeyEvent(scancode, Event::KEYBOARD_KEYDOWN) { }
Event Handler Methods:
bool EventHandler::EnqueueEvent(Event* event) {
if(event == NULL) return false;
try {
this->_eventQueue.push(event);
} catch (...) {
return false;
}
return true;
}
Event* EventHandler::DequeueEvent() {
if(this->_eventQueue.empty() == false) {
Event* result = new Event(*this->_eventQueue.front());
delete this->_eventQueue.front();
this->_eventQueue.pop();
return result;
}
return NULL;
}
Main Loop Sequence:
if(_eh->HasEvents()) {
Event* nxtEvent = _eh->DequeueEvent();
switch(nxtEvent->GetType()) {
case Event::KEYBOARD_KEYDOWN:
allegro_message("You pressed the %d key!", dynamic_cast<KeyboardKeyDownEvent*>(nxtEvent)->GetKey());
break;
default:
/* DO NOTHING */;
}
delete nxtEvent;
nxtEvent = NULL;
}
I know this is a slicing problem I just don't see why it's happening or how to fix it (Actually, now that I think about it, it's probably a "Can not convert to requested type" error). All throughout when I step through the program _scancode is the appropriate value, but the second the line dynamic_cast<KeyboardKeyDownEvent*>(nxtEvent)->GetKey() runs it throws the error. Double casting as dynamic_cast<KeyboardKeyDownEvent*>(dynamic_cast<KeyboardKeyEvent*>(nxtEvent))->GetKey() fails with the same error as well.
EDIT:
After some tweaking, this variant works perfectly:
if(_eh->HasEvents()) {
switch(_eh->PeekEvent()->GetType()) {
case Event::KEYBOARD_KEYDOWN:
allegro_message("You pressed the %s key!", scancode_to_name(dynamic_cast<KeyboardKeyDownEvent*>(_eh->PeekEvent())->GetKey()));
break;
case Event::MOUSE_BUTTONDOWN:{
Mouse::BUTTONS btn = dynamic_cast<MouseButtonDownEvent*>(_eh->PeekEvent())->GetButton();
if(btn == Mouse::BUTTON2) {
allegro_message("You pressed the %d button!", dynamic_cast<MouseButtonDownEvent*>(_eh->PeekEvent())->GetButton());
}
}
break;
default:
/* DO NOTHING */;
}
}
One solution to avoid slicing is to make the destructor of base class virtual, so in your case you can make ~Event() virtual:
class Event
{
public:
//...
virtual ~Event() {}
};
By the way, I'm wondering why you do the following:
//YOUR CODE : its causing the problem!
Event* EventHandler::DequeueEvent() {
if(this->_eventQueue.empty() == false) {
Event* result = new Event(*this->_eventQueue.front()); // WHY?
delete this->_eventQueue.front(); //WHY?
this->_eventQueue.pop();
return result;
}
return NULL;
}
Why don't you simply do this:
//Use it. Because it should not cause that probem
Event* EventHandler::DequeueEvent() {
if(this->_eventQueue.empty() == false) {
Event* result = this->_eventQueue.front();
this->_eventQueue.pop();
return result;
}
return NULL;
}
In Event* EventHandler::DequeueEvent() you have line
Event* result = new Event(*this->_eventQueue.front()); Here the slicing occurs.
You can do the following:
class Event {
public:
virtual Event* clone() {
// create a new instance and copy all the fields
}
}
Then override clone() in derived classes, e.g.
class KeyboardKeyEvent :public Event {
public:
...
virtual KeyboardKeyEvent* clone(); // note - it returns different type
}
Then change Event* EventHandler::DequeueEvent() :
Event* result = (*this->_eventQueue.front()).clone();
Your DequeueEvent method will always return an Event object, not any of the sub-classes that you are expecting.
Event* result = new Event(*this->_eventQueue.front());
Your Dequeue event should either return the actual reference it is caching, or your base Event class need to provide some sort of virtual copy operation that will provide a real clone.
Why are you copying the Event when you remove it from the queue? That's what is doing the slicing, since you're constructing the base class. Instead, return the pointer that was on the queue to the user.
As noted above, Event should have a virtual ~Event(), so that the recipient of the event can delete it properly. Otherwise, the concrete class destructor will not be properly run.
Event* EventHandler::DequeueEvent() {
if(this->_eventQueue.empty() == false) {
Event* result = this->_eventQueue.front();
this->_eventQueue.pop();
return result;
}
return NULL;
}