C++ Pointer crashes (Uninitialized) - c++

It seems this problem is the so-called dangling pointer problem. Basically I'm trying to parse a pointer into a function (that stores the pointer as a global variable) inside a class, and I want the pointer to be stored in that class and can be used now and then. So from inside the class, I can manipulate this pointer and its value which is outside of the class.
I simplified the code and re-created the situation as the following:
main.cpp
#include <iostream>
#include "class.h"
using namespace std;
void main() {
dp dp1;
int input = 3;
int *pointer = &input;
dp1.store(pointer);
dp1.multiply();
}
class.h
#pragma once
#include <iostream>
using namespace std;
class dp {
public:
void store(int *num); // It stores the incoming pointer.
void multiply(); // It multiplies whatever is contained at the address pointed by the incoming pointer.
void print();
private:
int *stored_input; // I want to store the incoming pointer so it can be used in the class now and then.
};
class.cpp
#include <iostream>
#include "class.h"
using namespace std;
void dp::store(int *num) {
*stored_input = *num;
}
void dp::multiply() {
*stored_input *= 10;
print();
}
void dp::print() {
cout << *stored_input << "\n";
}
There is no compile error but after running it, it crashes.
It says:
Unhandled exception thrown: write access violation.
this->stored_input was 0xCCCCCCCC.
If there is a handler for this exception, the program may be safely continued.
I pressed "break" and it breaks at the 7th line of class.cpp:
*stored_input = *num;

It is not a dangling pointer, but a not initialized, you probably want:
void dp::store(int *num) {
stored_input = num;
}

Related

C++ Pointer function to other class function

I need help with passing a function pointer on C++. I can't linkage one function for a class to other function. I will explain. Anyway I will put a code resume of my program, it is much larger than the code expose here but for more easier I put only the part I need to it works fine.
I have one class (MainSystem) and inside I have an object pointer to the other class (ComCamera). The last class is a SocketServer, and I want when the socket received any data, it sends to the linkage function to MainSystem.
ComCamera is a resource Shared with more class and I need to associate the functions ComCamera::vRecvData to a MainSystem::vRecvData or other function of other class for the call when receive data and send de data to the function class associate.
Can Anyone help to me?
EDDITED - SOLUTION BELOW
main.cpp
#include <iostream>
#include <thread>
#include <string>
#include <vector>
#include <cmath>
#include <string.h>
#include <stdio.h>
#include <exception>
#include <unistd.h>
using std::string;
class ComCamera {
public:
std::function<void(int, std::string)> vRecvData;
void vLinkRecvFunction(std::function<void(int, std::string)> vCallBack) {
this->vRecvData = vCallBack;
}
void vCallFromCamera() {
this->vRecvData(4, "Example");
};
};
class MainSystem {
private:
ComCamera *xComCamera;
public:
MainSystem(ComCamera *xComCamera) {
this->xComCamera = xComCamera;
this->xComCamera->vLinkRecvFunction([this](int iChannelNumber, std::string sData) {vRecvData(iChannelNumber, sData); });
}
void vRecvData(int iNumber, string sData) {
std::cout << "RECV Data From Camera(" + std::to_string(iNumber) + "): " << sData << std::endl;
};
};
int main(void) {
ComCamera xComCamera;
MainSystem xMainSystem(&xComCamera);
xComCamera.vCallFromCamera();
return 0;
}
Output will be:
MainSystem RECV Data From Camera(4): Example
You can have ComCamera::vRecvData be of type std::function<void(int, std::string)> and then have ComCamera::vLinkRecvFunction() be like this:
void ComCamera::vLinkRecvFunction(std::function<void(int, std::string)> callBack)
{
this->vRecvData = callBack;
}
and have MainSystem constructor be like this:
MainSystem::MainSystem(ComCamera *xComCamera)
{
using namespace std::placeholders;
this->xComCamera = xComCamera;
this->xComCamera->vLinkRecvFunction([this](int iNumber, std::string sData){vRecvData(number, sData);});
}
Still though the original question has way too much code to go through friend.
Here what you want :
#include<iostream>
using std::cout;
class A; //forward declare A
class B{
public:
void (A::*ptr)(int x); //Only declare the pointer because A is not yet defined.
};
class A{
public:
void increase_by(int x){
a+=x;
} // this function will be pointed by B's ptr
int a = 0; // assume some data in a;
B b; // creating B inside of A;
void analyze(int y){
(*this.*(b.ptr))(y);
} // Some function that analyzes the data of A or B; Here this just increments A::a through B's ptr
};
int main(){
A a; // creates A
cout<<a.a<<"\n"; // shows initial value of a
a.b.ptr = &A::increase_by; // defines the ptr that lies inside of b which inturns lies inside a
a.analyze(3); // calls the initialize method
(a.*(a.b.ptr))(3); // directly calls b.ptr to change a.a
cout<<a.a; // shows the value after analyzing
return 0;
}
Output will be :
0
6
I still don't get why would you do something like this. But maybe this is what you wanted as per your comments.
To know more read this wonderful PDF.

If the original variable is missing from the class containing the referenced member, why is it still accessible?

A member of a class is a reference to a local variable. When the local variable is destructed, and the object of this class still exists, you can access the destructed local variable through this object. Why?
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
class c2
{
public:
int& a;
c2(int & c):a(c)
{
}
};
int main()
{
c2 * p;
{
int i = 20;
p = new c2(i);
}
cout << p->a;
system("pause");
return 0;
}
As pointed out by some comments above, the behavior is actually undefined. See in particular the c++ reference on the Lifetime of a temporary:
a temporary bound to a reference in the initializer used in a
new-expression exists until the end of the full expression containing
that new-expression, not as long as the initialized object. If the
initialized object outlives the full expression, its reference member
becomes a dangling reference.
If you use gcc or clang you can compile the program with the option -fsanitize=address: it will crash with
ERROR: AddressSanitizer: stack-use-after-scope
Instead, you will not get any error if you modify your program as follows:
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
class c2
{
public:
int& a;
c2(int & c):a(c)
{
}
};
int main()
{
c2 * p;
{
int i = 20;
p = new c2(i);
cout << p->a;
}
delete p;
return 0;
}
(In the program I have inserted a delete p to avoid memory leak)

Pointer to a different instance.

How can such a code work correctly when the IWindow pointer clearly has an address to a ISheet class which has no method Say?
#include <iostream>
using namespace std;
class IWindow
{
private:
int p;
double f;
public:
void Say() { cout << "Say in IWindow"; }
};
class ISheet
{
public:
void foo() { cout << "ISheet::foo"; }
};
int main()
{
ISheet *sh = new ISheet();
int ptr = (int)sh;
IWindow *w = (IWindow*)ptr;
w->Say();
sh->foo();
return 0;
}
When compiled in Visual Studio 2015 it runs and executes with no problems, but I was expecting to get an error on line w->Say(). How is this possible?
It works by the grace of the almighty Undefined Behavior. Your functions don't try to access any data members of the containing class, they just write something to std::cout, which anyone can do.
What you've effectively done is
#include <iostream>
void IWindow_Say(void*)
{
std::cout << "Say in IWindow";
}
int main()
{
IWindow_Say(0xdeadbeef); // good luck with that pointer
}
You never used the pointer (which became this in your original example) so no side-effects were observed.

Instance of class only allows 1 method, or program crashes

I am learning classes and OOP, so I was doing some practice programs, when I came across the weirdest bug ever while programming.
So, I have the following files, beginning by my class "pessoa", located in pessoa.h:
#pragma once
#include <string>
#include <iostream>
using namespace std;
class pessoa {
public:
//constructor (nome do aluno, data de nascimento)
pessoa(string newname="asffaf", unsigned int newdate=1996): name(newname), DataN(newdate){};
void SetName(string a); //set name
void SetBornDate(unsigned int ); //nascimento
string GetName(); //get name
unsigned int GetBornDate();
virtual void Print(){}; // print
private:
string name; //nome
unsigned int DataN; //data de nascimento
};
Whose functions are defined in pessoa.cpp
#include "pessoa.h"
string pessoa::GetName ()
{
return name;
}
void pessoa::SetName(string a)
{
name = a;
}
unsigned int pessoa::GetBornDate()
{
return DataN;
}
void pessoa::SetBornDate(unsigned int n)
{
DataN=n;
}
A function, DoArray, declared in DoArray.h, and defined in the file DoArray.cpp:
pessoa** DoArray(int n)
{
pessoa* p= new pessoa[n];
pessoa** pointer= &p;
return pointer;
}
And the main file:
#include <string>
#include <iostream>
#include "pessoa.h"
#include "DoArray.h"
#include <cstdio>
using namespace std;
int main()
{
//pessoa P[10];
//cout << P[5].GetBornDate();
pessoa** a=DoArray(5);
cerr << endl << a[0][3].GetBornDate() << endl;
cerr << endl << a[0][3].GetName() << endl;
return 0;
}
The weird find is, if I comment one of the methods above, "GetBornDate" or GetName, and run, the non-commented method will run fine and as supposed. However, if both are not commented, then the first will run and the program will crash before the 2nd method.
Sorry for the long post.
Let's look into this function:
int *get()
{
int i = 0;
return &i;
}
what is the problem with it? It is returning pointer to a local variable, which does not exist anymore when function get() terminates ie it returns dangling pointer. Now your code:
pessoa** DoArray(int n)
{
pessoa* p= new pessoa[n];
return &p;
}
do you see the problem?
To clarify even more:
typedef pessoa * pessoa_ptr;
pessoa_ptr* DoArray(int n)
{
pessoa_ptr p= whatever;
return &p;
}
you need to understand that whatever you assign to p does not change lifetime of p itself. Pointer is the same variable as others.

How Do I Store Objects in a Object in a Vector? (C++)

I hope this is not a stupid question. Basically I would like to access a string stored in a Class (Statement is the name I am using) in a vector of type Statement. Basically I am trying to store objects in a dynamic hierarchy of objects.
Types.cpp:
#include<iostream>
#include<fstream>
#include <string>
#include <vector>
using namespace std;
class Statement{
public:
vector<string> Inner_String;
vector<Statement> Inner_Statement;
string contents;
void set_contents (string);
string get_contents(){ return contents;}
void new_string(string);
string get_string(int v){return Inner_String[v];}
void new_Inner_Statement(Statement);
Statement get_Inner_Statement(int v){return Inner_Statement[v];}
};
void Statement::set_contents(string s){
contents = s;
}
void Statement::new_string(string s){
Inner_String.push_back(s);
}
void Statement::new_Inner_Statement(Statement s){
Inner_Statement.push_back(s);
}
Main method:
#include <iostream>
#include "FileIO.h"
#include "Types.h"
using namespace std;
int main()
{
Statement test;
test.new_Inner_Statement(Statement());
Statement a = test.get_Inner_Statement(0);
a.set_contents("words");
cout << a.get_contents();
test.get_Inner_Statement(0).set_contents("string");
cout << test.get_Inner_Statement(0).get_contents();
return 0;
}
What happens is
cout << a.get_contents()
returns its string while
cout << test.get_Inner_Statement(0).get_contents()
does not.
Look at this piece of code:
test.get_Inner_Statement(0).set_contents("string");
^^^^^^^^^^^^^^^^^^^^^^^^^^^
It calls this function:
Statement get_Inner_Statement(int v)
which returns a copy object (temporary) of type statement. On this object, you calls set_contents function, at which cease to exists at the end of the call.
Then, you call:
test.get_Inner_Statement(0).get_contents();
that creates a new temporary, from the unchanged statement, and try to get its contents.