Pass / copy pointer to another pointer - c++

I have a pointer code as follows :
class NsObject : public TclObject, public Handler {
public:
NsObject();
virtual ~NsObject();
virtual void recv(Packet*, Handler* callback = 0) = 0;
virtual void recv(Packet* p, const char* s);
}
NsObject* uptargetTX;
NsObject* uptarget_;
void NsObject::recv(Packet *p, const char*)
{
Packet::free(p);
}
if (NodeType_ == TX) {
uptarget_->recv(ppp, (Handler*) 0);
*uptargetTX = *uptarget_; //in this line error happens
}
I want to pass/copy the pointer uptarget_ to uptargetTX by using *uptargetTX = *uptarget_; but something goes wrong
segmentation fault (core dumped)
Then I change to uptargetTX = uptarget_; but same error occurs. How to remove this error ?

uptargetTX and uptarget_ are unininitialized, so they point to random memory locations, so access causes a segmentation fault. Depending on what you are trying to do, you probably have to allocate memory first for example like this: NsObject* uptargetTX = new NsObject

I have no idea of what your code does but this
NsObject* uptarget_;
uptarget_->recv(ppp, (Handler*) 0); <- dereference the pointer
is wrong in the first place: you need to initialize that pointer to something valid before.
The rest is also wrong for the same reason.

Related

Exception Unhanded - This was Nullpointer C++

I have two classes Display and Snake.
With the Display class I hols some functionality that involves creating buffer and etc.
I'm trying to do something that seem logical to me but apparently not to the compiler
cSnake.h
class Snake
{
public:
Snake();
void printSnake();
~Snake();
private:
Display* display;
};
cSnake.cpp
Snake::Snake() {}
void Snake::printSnake() {
display->PrintCharecter(40, 15, L" Hello World ");
}
Snake::~Snake() {}
This is the Display class
Class Display{
public:
void CreateScreenBuffer();
void DisplayFrame();
void PrintCharecter(int x, int y LPCWSTR text);
private:
int nScreenWidth;
int nScreenHeight;
wchar_t *screen;
}
// The function that I try to call
void Display::PrintCharecter(int x, int y, LPCWSTR text) {
wsprintf(&screen[y* nScreenWidth + x], text); // exception is thrown here
}
Calling it in the main
Snake snake
snake.printSnake();
Then it throws unhanded exception that.
Being NULL pointer. I bit confused here, which one the NULL pointer is it the function call or the array screen?
The error is that the Display pointer points to nothing, which is an uninitialized pointer. A pointer only stores the address of the memory, not the actual memory. Therefore you have only created a pointer, but not the memory it points to on the heap. This means that in your constructor, you should create a new display object on the heap and assign that to your pointer.
Snake::Snake()
{
display = new Display;
}
This will give you your expected behaviour.
It's also important to note that you must delete the memory the pointer points to otherwise it will just float there until the program ends. Therefore your Snake destructor should delete display:
Snake::~Snake()
{
delete display;
}

Understanding why there is an Segmentation Fault

I have some code and I try to figure out, why I'm getting an segmentation fault here:
I add a SpeedEffect to a EffectStack, this works quite well. But if I try to remove one of the Effects (which are already on the stack) I have to call effect.removeEffect(). This causes a segmentation fault.
If I try to call effect.removeEffect() from the TestStack() function, it works well (and prints the expected "speed effect removed" on the console)
void Test::testStack() {
Story* st = new Story; //<-- only needed for initialization of an Effect
Veins::TraCIMobility* mob = new Veins::TraCIMobility; //<-- only needed for initialization of an Effect
SpeedEffect a = SpeedEffect(1.0, st, mob);
a.removeEffect(); //<-- This one works quite well
(&a)->removeEffect(); //<-- Clearly, this works too
EffectStack s;
s.addEffect(&a); //<-- Adds a Effect to the effect Stack
assert(s.getEffects().size() == 1);
s.removeEffect(&a); //<-- Try to remove effect from stack
}
The Stack and the Effect are implemented as following:
class Effect {
public:
Effect(Story* story, Veins::TraCIMobility* car) :
m_story(story), m_car(car) {}
virtual void removeEffect() = 0;
private:
Story* m_story;
protected:
Veins::TraCIMobility* m_car;
};
class SpeedEffect : public Effect {
public:
SpeedEffect(double speed, Story* story, Veins::TraCIMobility* car):
Effect(story, car), m_speed(speed){}
void removeEffect() {
std::cout << "speed effect removed" << std::endl;
}
private:
double m_speed;
};
class EffectStack {
public:
void addEffect(Effect* effect) {
if(std::count(m_effects.begin(), m_effects.end(), effect) == 0) {
m_effects.push_back(effect);
}
}
void removeEffect(Effect* effect) {
if(effect == m_effects.back()) {
//effect is pointing on the same address like its doing before, but causes the seg fault
m_effects.back()->removeEffect(); //<--- Seg Fault here!!
effect->removeEffect(); //<-- if I use this, seg fault too
m_effects.pop_back();
}else {
removeFromMiddle(effect);
}
}
const std::vector<Effect*>& getEffects() {
return m_effects;
}
private:
std::vector<Effect*> m_effects;
};
I hope this code is enough, I have removed all functions which are not called by the testing scenario.
Is there any problem, because the address of the speedEffect a becomes invalid in the Stack?
Maybe you can help me with this.
New thoughts about the question:
No I have tested a bit more, which makes me even more confused:
void dofoo(SpeedEffect* ef) {
ef->removeEffect(); //<-- breaks with a segmentation fault
}
void Test::testStack() {
Story* st = new Story;
Veins::TraCIMobility* mob = new Veins::TraCIMobility;
SpeedEffect e = SpeedEffect(3.0, st, mob);
e.removeEffect(); //<-- Works fine
(&e)->removeEffect(); //<-- Works fine also
dofoo(&a); //<-- Jumps into the dofoo() function
}
This may not help you, but persisting the address of stack-based objects is usually not a great idea. In your code above it's potentially okay since you know EffectStack won't outlive your effect.
Does the crash still occur if you do:
SpeedEffect* a = new SpeedEffect(1.0, st, mob);
(and adjust the rest of the code accordingly?) This will leak memory of course, but it will tell you if the problem is SpeedEffect being destroyed. Another option is to give SpeedEffect a destructor (and Effect a virtual destructor) and set a breakpoint inside to see when the the compiler is destroying 'a'.
Story* st = new Story; //<-- only needed for initialization of an Effect
Veins::TraCIMobility* mob = new Veins::TraCIMobility; //<-- only needed for initialization
I don't see the delete st and delete mob - there is memory allocated for these objects inside void Test::testStack() but not explicitly released.
add these two statement at the end of the function and try again.
I have found the problem.
I'm using the omnet Simulation framework and there is something unexpected happening if I instanciate the TraciMobility..
So without it, there is no error..

Getting segmentation fault when reassigning pointer

Here's the fragment of a large code that is causing the error:
Class TreeNode {
private:
int level;
TreeNode* parentNode;
public:
TreeNode() {
level = 0;
parentNode = NULL;
}
void setParent (TreeNode* n) {
parentNode = n; // <- this reassignment is causing segmentation fault
}
}
How can I reassign properly the pointer variable parentNode?
As #galinette tried to point it out, I might have called setParent from a null pointer. But, I check it beforehand in this way:
if (candidateChild != NULL) {
candidateChild -> setParent(this); // <- I checked that both this and candidatChild are not NULL
}
The setParent fonction has no problem by itself. But you likely called it from an invalid pointer to a TreeNode (such as a null/uninitialized/deleted pointer)
Your code is valid, the error comes from another part that you did not post.
You have to use TreeNode** parentNode as a private field, and use *parentNode=&n for assignment.

Send a variable on the heap to another thread

I have a strange problem in C++. An address of a Boolean gets "destroyed" but it doesn't get touched. I know that there are better ways to accomplish what I try to do, but I want to know what I do wrong.
I have a main class; this main class contains a vector of another class. There is a strange problem when a new instance gets created of this object.
This is how my code works:
There will start a thread when the constructor gets called of the β€œ2nd” object. This thread gets as Parameter a struct. This is the struct:
struct KeyPressData
{
vector<bool> *AutoPressStatus;
vector<int> *AutoPressTime;
bool * Destroy;
bool * Ready;
};
The struct gets filled in the constructor:
MultiBoxClient::MultiBoxClient()
{
//init data
DestroyThread = new bool;
ReadyThread = new bool;
AutoThreadData = new KeyPressData;
//Reseting data
*DestroyThread = false;
*ReadyThread = false;
//KeyPressData configurating
AutoThreadData->AutoPressStatus = &AutoPressStatus;
AutoThreadData->AutoPressTime = &AutoPressTime;
AutoThreadData->Destroy = DestroyThread;
AutoThreadData->Ready = ReadyThread;
//Start the keypress thread
CreateThread(NULL,NULL,(LPTHREAD_START_ROUTINE)AutoKeyThread,AutoThreadData,NULL,NULL);
}
This is the defenition of MultiBoxClient:
class MultiBoxClient
{
private:
HWND ClientHandle;
vector<bool> KeyPresses;
vector<bool> AutoPressStatus;
vector<int> AutoPressTime;
KeyPressData * AutoThreadData;
bool * DestroyThread;
bool * ReadyThread;
public:
MultiBoxClient();
MultiBoxClient(HWND Handle);
~MultiBoxClient();
void EditClient(HWND Handle);
void SendKeypress(vector<bool> KeyStatus);
void SendKeyCombination(unsigned int id);
void AutoCast(int Key,unsigned int Time,bool status);
bool IsAlive();
};
MultiBoxClient is created this way:
int main()
{
MultiboxControler * MainControler = new MultiboxControler;
while(true)
{
Sleep(1000);
}
delete MainControler;
return false;
}
As long as the constructor is running will the program run fine. But when the constructor closes the address of the AutoThreadData->Destroy will get corrupted. The program will crash when I call the value of the pointer.
 
void WINAPI AutoKeyThread(void * ThreadData)
{
KeyPressData * AutoThreadData = (KeyPressData*)ThreadData;
while(true)
{
if(*AutoThreadData->Destroy == true) //CRASH
{
*AutoThreadData->Ready = true;
return;
}
Sleep(100);
}
}
What did I test:
I logged the address of the AutoThreadData and the AutoThreadData->Destroy when the constrcutor is running and clossed; the AutoThreadData address is equal to AutoThreadData when the constructor is closed. So there is no problem here.
The address of AutoThreadData->Destroy gets destroyed when the constructor is closed. But how can this happen? The Boolean is on the heap and the KeyPressData struct (AutoThreadData) is on the heap.
Destroy before: 00A85328
Destroy after: FEEEFEEE
Can someone maby explain why this crash?
I know that I can send a pointer to my class to the thread. But I want to know what goes wrong here. That way I can learn from my mistakes.
Could someone help me with this problem?
I guess that you made a mistake with the vector, use a class pointer, instead of the class itself, like this:
vector<class*> //instead of vector<class>
0xFEEEFEEE is an indication of freed memory. That is, you AutoThreadData was deleted, and it was not on your worker thread which is in endless loop. So, it has to be your main thread and perhaps destructor, which you did not show.
Whereever you destroy/free your KeyPressData instance, comment this out or set a breakpoint there to find out where it is taking place.

very basic c++: seg fault when doing cross class pointer assignment with malloc

In the following code, 'buf' is malloced, but then why accessing its member gives seg fault?
class tool{
...
void do(char* buf){
buf = malloc(100);
... //init buf[0], buf[1], etc
}
};
class user{
...
tool *tl;
char *buf;
user(){
tl = new tool;
tl -> do(buf);
cout<<buf[1]<<endl; //---> gives seg fault! Why?
}
};
You didn't write to the copy of buf in user. All you did was allocate the memory, store it to a local variable in do() and then forget about it when do() returned.
You need do() to receive a char**. Only if you do it this way can do() return the newly allocated memory to the caller.
void _do(char** buf){
*buf = (char*)malloc(100);
... //init buf[0], buf[1], etc
}
...
tl -> _do(&buf);
Of course, since this is C++ I wonder why you don't use references and std::string, but perhaps this is illustrative code.