Program crashing when accessing a specific struct member - c++

No matter what I do I can seem to access x even though it is implemented nearly the same as y. Im unsure If its some kind of memory access issue. The program breaks at the first access of x with no compile errors or warnings.
Calling step in the CPU works fine if x is not there. Any help is wonderful.
ESys.h
#pragma once
namespace ESYS
{
struct InterconnectI
{
int y;
std::vector<uint8_t>& Ip;
std::vector<uint8_t>& Ir;
InterconnectI(std::vector<uint8_t>& p, std::vector<uint8_t>& r);
~InterconnectI(){};
void hi(int n);
};
struct CPUI
{
int x;
CPUI();
~CPUI(){};
void step(InterconnectI* i);
};
struct SystemI
{
CPUI* CPU;
InterconnectI* Interconnect;
SystemI(std::vector<uint8_t>& p, std::vector<uint8_t>& r);
void Step();
};
}
ESys.cpp
#include "stdafx.h"
#include "ESys.h"
namespace ESYS
{
InterconnectI::InterconnectI(std::vector<uint8_t>& p, std::vector<uint8_t>& r) : Ip(p), Ir(r)
{
y = 0;
}
void InterconnectI::hi(int n)
{
std::cout << "Interconnect " << n << std::endl;
}
CPUI::CPUI()
{
x = 5;
}
void CPUI::step(InterconnectI* i)
{
std::cout << "Step CPU -> " x; //Accessing doesn't work...
i->hi(x); //Passing doesn't work...
}
SystemI::SystemI(std::vector<uint8_t>& p, std::vector<uint8_t>& r)
{
CPUI* CPU = new CPUI();
InterconnectI* Interconnect = new InterconnectI(p, r);
}
void SystemI::Step()
{
CPU->step(Interconnect);
}
}
Main.cpp
#include "stdafx.h"
#include "ESys.h"
std::vector<uint8_t> pDat;
std::vector<uint8_t> rDat;
int main(int argc, const char *argv[])
{
ESYS::SystemI ESystem(pDat, rDat);
ESystem.Interconnect->y = 11;
for (;;)
{
ESystem.Step();
}
return 0;
}

The problem is here:
SystemI::SystemI(std::vector<uint8_t>& p, std::vector<uint8_t>& r)
{
CPUI* CPU = new CPUI();
InterconnectI* Interconnect = new InterconnectI(p, r);
}
The results of new are assigned to the local variables CPU and Interconnect. The data members SystemI::CPU and SystemI::Interconnect remain uninitialized.

Related

Comparison of methods for multithreading with multiple objects in C++

I'm working on C++ code for a 'manager' class that runs a process in multiple member objects in separate threads and returns a set of values. I see three basic ways I can implement this:
create each thread with the member function for the relevant object and a callback mechanism to return the values;
provide an auxiliary function in the manager class that calls the member function for a specified object and create separate threads with this auxiliary function; or
create each thread with the member function for the relevant object (as in method #1) and pass pointers to variables to hold the return values.
My question is, are there compelling reasons to choose one method over the other, in terms of performance or other factors, keeping in mind the fact that the actual application would have an array or vector of an indeterminate number of objects (unlike the examples below)?
An example of the first method would look like this:
#include <thread>
#include <iostream>
#include <functional>
using namespace std;
using namespace std::placeholders;
typedef function<void(string, int)> Callback;
class Processor {
private:
string name;
Callback cb_func;
public:
Processor(string nme, Callback f) : name(nme), cb_func(f) { }
void do_stuff(int lim) { cb_func(name, rand() % lim); }
};
class Manager {
private:
Processor *p0, *p1;
public:
Manager() {
p0 = new Processor("lizard", std::bind(&Manager::report, this, _1, _2));
p1 = new Processor("ferret", std::bind(&Manager::report, this, _1, _2));
}
~Manager() {
delete p0;
delete p1;
}
void manage() {
thread t0 = thread(&Processor::do_stuff, p0, 100);
thread t1 = thread(&Processor::do_stuff, p1, 100);
t0.join();
t1.join();
}
void report(string source, int value) {
cout << source << " reports " << value << endl;
}
};
int main() {
Manager the_dude;
the_dude.manage();
return 0;
}
An example of the second method would look like this:
#include <thread>
#include <iostream>
using namespace std;
class Processor {
private:
string name;
public:
Processor(string nme) : name(nme) { }
int do_stuff(int lim) { return rand() % lim; }
string get_name() { return name; }
};
class Manager {
private:
Processor *p0, *p1;
public:
Manager() {
p0 = new Processor("lizard");
p1 = new Processor("ferret");
}
~Manager() {
delete p0;
delete p1;
}
void work(Processor *p, int lim) {
cout << p->get_name() << " reports " << p->do_stuff(lim) << endl;
}
void manage() {
thread t0 = thread(&Manager::work, this, p0, 100);
thread t1 = thread(&Manager::work, this, p1, 100);
t0.join();
t1.join();
}
};
int main() {
Manager the_dude;
the_dude.manage();
return 0;
}
And an example of the third method would look like this:
#include <thread>
#include <iostream>
using namespace std;
class Processor {
private:
string name;
public:
Processor(string nme) : name(nme) { }
void do_stuff(int lim, string *nme, int *val) { *nme = name; *val = rand() % lim; }
};
class Manager
{
private:
Processor *p0, *p1;
string s0, s1;
int v0, v1;
public:
Manager() {
p0 = new Processor("lizard");
p1 = new Processor("ferret");
}
~Manager() {
delete p0;
delete p1;
}
void manage() {
thread t0 = thread(&Processor::do_stuff, p0, 100, &s0, &v0);
thread t1 = thread(&Processor::do_stuff, p1, 100, &s1, &v1);
t0.join();
t1.join();
report(s0, v0);
report(s1, v1);
}
void report(string source, int value) {
cout << source << " reports " << value << endl;
}
};
int main()
{
Manager the_dude;
the_dude.manage();
return 0;
}

Pass a function of object of any type to another object in C++

I'm creating a node system (similar to eg. UE4 or Blender's Cycles) in which i can create nodes of different types and use them later. At the moment I have 2 classes of nodes with output functions like these:
class InputInt
{
public:
int output()
{
int x;
std::cin>>x;
return x;
}
};
class RandomInt
{
public:
int rand10()
{
int x;
x = rand()%10;
return x;
}
int rand100()
{
int x;
x = rand()%100;
return x;
}
};
I don't pass anything to these nodes. Now I want to create a node which takes and output function from and object of one of above classes. Here is how I implemented it to use InputInt node only:
class MultiplyBy2
{
typedef int (InputInt::*func)();
func input_func;
InputInt *obj;
public:
MultiplyBy2(InputInt *object, func i): obj(object), input_func(i) {}
int output()
{
return (obj->*input_func)()*2;
}
};
Having this I can create and use object of MultiplyBy2 in main() and it works perfectly.
int main()
{
InputInt input;
MultiplyBy2 multi(&input, input.output);
std::cout<<multi.output()<<std::endl;
}
It doesn't obviously work for object of RandomInt as I have to pass *InputInt object to MultiplyBy2 object. Is there a way to make MultiplyBy2 take any kind of an object with its output function eg. like this?
int main()
{
RandomInt random;
MultiplyBy2 multi2(&random, random.rand10);
std::cout<<multi2.output()<<std::endl;
}
An alternative approach, using a common base class with virtual methods:
#include <iostream>
struct IntOp {
virtual int get() = 0;
};
struct ConstInt: IntOp {
int n;
explicit ConstInt(int n): n(n) { }
virtual int get() override { return n; }
};
struct MultiplyIntInt: IntOp {
IntOp *pArg1, *pArg2;
MultiplyIntInt(IntOp *pArg1, IntOp *pArg2): pArg1(pArg1), pArg2(pArg2) { }
virtual int get() override { return pArg1->get() * pArg2->get(); }
};
int main()
{
ConstInt i3(3), i4(4);
MultiplyIntInt i3muli4(&i3, &i4);
std::cout << i3.get() << " * " << i4.get() << " = " << i3muli4.get() << '\n';
return 0;
}
Output:
3 * 4 = 12
Live Demo on coliru
As I mentioned std::function in post-answer conversation with OP, I fiddled a bit with this idea and got this:
#include <iostream>
#include <functional>
struct MultiplyIntInt {
std::function<int()> op1, op2;
MultiplyIntInt(std::function<int()> op1, std::function<int()> op2): op1(op1), op2(op2) { }
int get() { return op1() * op2(); }
};
int main()
{
auto const3 = []() -> int { return 3; };
auto const4 = []() -> int { return 4; };
auto rand100 = []() -> int { return rand() % 100; };
MultiplyIntInt i3muli4(const3, const4);
MultiplyIntInt i3muli4mulRnd(
[&]() -> int { return i3muli4.get(); }, rand100);
for (int i = 1; i <= 10; ++i) {
std::cout << i << ".: 3 * 4 * rand() = "
<< i3muli4mulRnd.get() << '\n';
}
return 0;
}
Output:
1.: 3 * 4 * rand() = 996
2.: 3 * 4 * rand() = 1032
3.: 3 * 4 * rand() = 924
4.: 3 * 4 * rand() = 180
5.: 3 * 4 * rand() = 1116
6.: 3 * 4 * rand() = 420
7.: 3 * 4 * rand() = 1032
8.: 3 * 4 * rand() = 1104
9.: 3 * 4 * rand() = 588
10.: 3 * 4 * rand() = 252
Live Demo on coliru
With std::function<>, class methods, free-standing functions, and even lambdas can be used in combination. So, there is no base class anymore needed for nodes. Actually, even nodes are not anymore needed (explicitly) (if a free-standing function or lambda is not counted as "node").
I must admit that graphical dataflow programming was subject of my final work in University (though this is a long time ago). I remembered that I distinguished
demand-driven execution vs.
data-driven execution.
Both examples above are demand-driven execution. (The result is requested and "pulls" the arguments.)
So, my last sample is dedicated to show a simplified data-driven execution (in principle):
#include <iostream>
#include <vector>
#include <functional>
struct ConstInt {
int n;
std::vector<std::function<void(int)>> out;
ConstInt(int n): n(n) { eval(); }
void link(std::function<void(int)> in)
{
out.push_back(in); eval();
}
void eval()
{
for (std::function<void(int)> &f : out) f(n);
}
};
struct MultiplyIntInt {
int n1, n2; bool received1, received2;
std::vector<std::function<void(int)>> out;
void set1(int n) { n1 = n; received1 = true; eval(); }
void set2(int n) { n2 = n; received2 = true; eval(); }
void link(std::function<void(int)> in)
{
out.push_back(in); eval();
}
void eval()
{
if (received1 && received2) {
int prod = n1 * n2;
for (std::function<void(int)> &f : out) f(prod);
}
}
};
struct Print {
const char *text;
explicit Print(const char *text): text(text) { }
void set(int n)
{
std::cout << text << n << '\n';
}
};
int main()
{
// setup data flow
Print print("Result: ");
MultiplyIntInt mul;
ConstInt const3(3), const4(4);
// link nodes
const3.link([&mul](int n) { mul.set1(n); });
const4.link([&mul](int n) { mul.set2(n); });
mul.link([&print](int n) { print.set(n); });
// done
return 0;
}
With the dataflow graph image (provided by koman900 – the OP) in mind, the out vectors represent outputs of nodes, where the methods set()/set1()/set2() represent inputs.
Output:
Result: 12
Live Demo on coliru
After connection of graph, the source nodes (const3 and const4) may push new results to their output which may or may not cause following operations to recompute.
For a graphical presentation, the operator classes should provide additionally some kind of infrastructure (e.g. to retrieve a name/type and the available inputs and outputs, and, may be, signals for notification about state changes).
Surely, it is possible to combine both approaches (data-driven and demand-driven execution). (A node in the middle may change its state and requests new input to push new output afterwards.)
You can use templates.
template <typename UnderlyingClass>
class MultiplyBy2
{
typedef int (UnderlyingClass::*func)();
func input_func;
UnderlyingClass *obj;
public:
MultiplyBy2(UnderlyingClass *object, func i) : obj(object), input_func(i) {}
int output()
{
return (obj->*input_func)() * 2;
}
};
int main()
{
// test
InputInt ii;
MultiplyBy2<InputInt> mii{ &ii, &InputInt::output };
RandomInt ri;
MultiplyBy2<RandomInt> mri{ &ri, &RandomInt::rand10 };
}
This is a bit convoluted. However I think you should be making an interface or class that returns a value and the objects should inherit from this. Then the operator class can take any class that inherits from the base/interface. Eg Make an BaseInt class that stores an int and has the output method/ RandomInt and InputInt should inherit from BaseInt

function pointer for different functions with different data types or parameter

i have this code which uses a function pointer to point 3 functions sum, subtract, mul. it works well. but now the problem is that i have functions with different no.of parameters and different data types. how to implement this.
int add(int a, int b)
{
cout<<a+b;
}
int subtract(int a, int b)
{
cout<<a-b;
}
int mul(int a, int b)
{
cout<<a*b;
}
int main()
{
int (*fun_ptr_arr[])(int, int) = {add, subtract, mul};
unsigned int ch, a = 15, b = 10,c=9;
ch=2;
if (ch > 4) return 0;
(*fun_ptr_arr[ch])(a, b);
return 0;
}
The simple answer is that technically you can't do this. You could do some manipulations using an array as input for all these functions, but you will still have to know exactly what to pass to each function. From a software engineering perspective, you should not do this - I suggest you take a look at the nice answers here: C++ Function pointers with unknown number of arguments
A slightly different approach using objects to implement the required behavior. In order to have a truly generic kind of solution, we need to use Interfaces.
Dismantle the data and operation i.e keep them separately.
//Interface which describes any kind of data.
struct IData
{
virtual ~IData()
{
}
};
//Interface which desribes any kind of operation
struct IOperation
{
//actual operation which will be performed
virtual IData* Execute(IData *_pData) = 0;
virtual ~IOperation()
{
}
};
Now, every operation knows the kind of data it work on and will expect that kind of data only.
struct Operation_Add : public IOperation
{
//data for operation addition.
struct Data : public IData
{
int a;
int b;
int result;
};
IData* Execute(IData *_pData)
{
//expected data is "Operation_Add::Data_Add"
Operation_Add::Data *pData = dynamic_cast<Operation_Add::Data*>(_pData);
if(pData == NULL)
{
return NULL;
}
pData->result = pData->a + pData->b;
return pData;
}
};
struct Operation_Avg : public IOperation
{
//data for operation average of numbers.
struct Data : public IData
{
int a[5];
int total_numbers;
float result;
};
IData* Execute(IData *_pData)
{
//expected data is "Operation_Avg::Data_Avg"
Operation_Avg::Data *pData = dynamic_cast<Operation_Avg::Data*>(_pData);
if(pData == NULL)
{
return NULL;
}
pData->result = 0.0f;
for(int i = 0; i < pData->total_numbers; ++i)
{
pData->result += pData->a[i];
}
pData->result /= pData->total_numbers;
return pData;
}
};
Here, is the operation processor, the CPU.
struct CPU
{
enum OPERATION
{
ADDITION = 0,
AVERAGE
};
Operation_Add m_stAdditionOperation;
Operation_Avg m_stAverageOperation;
map<CPU::OPERATION, IOperation*> Operation;
CPU()
{
Operation[CPU::ADDITION] = &m_stAdditionOperation;
Operation[CPU::AVERAGE] = &m_stAverageOperation;
}
};
Sample:
CPU g_oCPU;
Operation_Add::Data stAdditionData;
stAdditionData.a = 10;
stAdditionData.b = 20;
Operation_Avg::Data stAverageData;
stAverageData.total_numbers = 5;
for(int i = 0; i < stAverageData.total_numbers; ++i)
{
stAverageData.a[i] = i*10;
}
Operation_Add::Data *pResultAdd = dynamic_cast<Operation_Add::Data*>(g_oCPU.Operation[CPU::ADDITION]->Execute(&stAdditionData));
if(pResultAdd != NULL)
{
printf("add = %d\n", pResultAdd->result);
}
Operation_Avg::Data *pResultAvg = dynamic_cast<Operation_Avg::Data*>(g_oCPU.Operation[CPU::AVERAGE]->Execute(&stAverageData));
if(pResultAvg != NULL)
{
printf("avg = %f\n", pResultAvg->result);
}
If you have the following functions
int f1(int i);
int f2(int i, int j);
You can define a generic function type like this
typedef int (*generic_fp)(void);
And then initialize your function array
generic_fp func_arr[2] = {
(generic_fp) f1,
(generic_fp) f2
};
But you will have to cast the functions back
int result_f1 = ((f1) func_arr[0]) (2);
int result_f2 = ((f2) func_arr[1]) (1, 2);
Obviously, it does not look like a good way to build a program
To make code look a little bit better you can define macros
#define F1(f, p1) ((f1)(f))(p1)
#define F2(f, p1, p2) ((f2)(f))(p1, p2)
int result_f1 = F1(func_arr[0], 2);
int result_f2 = F2(func_arr[1], 1, 2);
EDIT
Forgot to mention, you also have to define a type for every type of function
typedef int (*fi)(int); // type for function of one int param
typedef int (*fii)(int, int); // type for function of two int params
And to then cast stored pointers to those types
int result_f1 = ((fi) func_arr[0]) (2);
int result_f2 = ((fii) func_arr[1]) (1, 2);
Here is a complete example
#include <iostream>
typedef int (*generic_fp)(void);
typedef int (*fi)(int); // type for function of one int param
typedef int (*fii)(int, int); // type for function of two int params
#define F1(f, p1) ((fi)(f))(p1)
#define F2(f, p1, p2) ((fii)(f))(p1, p2)
int f1(int i);
int f2(int i, int j);
int main()
{
generic_fp func_arr[2] = {
(generic_fp) f1,
(generic_fp) f2
};
int result_f1_no_macro = ((fi) func_arr[0]) (2);
int result_f2_no_macro = ((fii) func_arr[1]) (1, 2);
int result_f1_macro = F1(func_arr[0], 2);
int result_f2_macro = F2(func_arr[1], 1, 2);
std::cout << result_f1_no_macro << ", " << result_f2_no_macro << std::endl;
std::cout << result_f1_macro << ", " << result_f2_macro << std::endl;
return 0;
}
int f1(int i)
{
return i * 2;
}
int f2(int i, int j)
{
return i + j;
}
The code above produces the following output
4, 3
4, 3

Issues creating a vector of class object in c++

I created the following class
#include "cliques.h"
#include "vector"
#include <iostream>
using namespace std;
cliques::cliques(){
}
cliques::cliques(int i) {
clique.push_back(i);
clique_prob = 1;
mclique_prob = 1;
}
cliques::cliques(const cliques& orig) {
}
cliques::~cliques() {
}
void cliques::addvertex(int i) {
clique.push_back(i);
}
double cliques::getclique_prob() const {
return clique_prob;
}
double cliques::getMaxclique_prob() const {
return mclique_prob;
}
void cliques::showVertices() {
for (vector<int>::const_iterator i = clique.begin(); i !=clique.end(); ++i)
cout << *i << ' ';
cout << endl;
}
vector<int> cliques::returnVector() {
return clique;
}
void cliques::setclique_prob(double i) {
clique_prob = i;
}
void cliques::setMaxclique_prob(double i) {
mclique_prob = i;
}
Here's the header file
#include "vector"
#ifndef CLIQUES_H
#define CLIQUES_H
class cliques {
public:
void addvertex(int i);
cliques();
cliques(int i);
cliques(const cliques& orig);
virtual ~cliques();
double getclique_prob() const;
double getMaxclique_prob() const;
void showVertices();
std::vector<int> returnVector();
void setclique_prob(double i);
void setMaxclique_prob(double i);
private:
float clique_prob;
float mclique_prob;
std::vector <int> clique;
};
#endif /* CLIQUES_H */
I want to create a vector of these objects in order to implement a heap
int main(int argc, char** argv) {
cliques temp(1);
cliques temp1(2);
temp.setclique_prob(0.32);
temp.setclique_prob(0.852);
temp.showVertices();
temp1.showVertices();
vector <cliques> max_heap;
max_heap.push_back(temp);
max_heap.push_back(temp1);
double x =max_heap.front().getclique_prob();
cout<<"prob "<<x<<endl;
cliques y = max_heap.front();
y.showVertices();
//make_heap (max_heap.begin(),max_heap.end(),max_iterator());
//sort_heap (max_heap.begin(),max_heap.end(),max_iterator());
return 0;
}
For reasons unknown to me none of my class functions work properly after i create my vector, meaning that while the following function works as intended
temp.showVertices()
the next one doesn't,
y.showVertices()
You miss implementation for
cliques::cliques(const cliques& orig) {
}
STL vector uses copy constructor inside when you add values to it. As your cliques class does not allocate any memory, you can just remove the copy constructor from the code and compiler will generate one for you.

Decrease operation in fibonacci heap, boost

I'm trying to use in my implementation the fibonacci heap from boost but my program crashes, when I calling decrease function, this the example (W is a simple class):
struct heap_data
{
boost::heap::fibonacci_heap<heap_data>::handle_type handle;
W* payload;
heap_data(W* w)
{
payload = w;
}
bool operator<(heap_data const & rhs) const
{
return payload->get_key() < rhs.payload->get_key();
}
};
int main()
{
boost::heap::fibonacci_heap<heap_data> heap;
vector<heap_data> A;
for (int i = 0; i < 10; i++)
{
W* w = new W(i, i + 3);
heap_data f(w);
A.push_back(f);
boost::heap::fibonacci_heap<heap_data>::handle_type handle = heap.push(f);
(*handle).handle = handle; // store handle in node
}
A[5].payload->decr();
heap.decrease(A[5].handle);
return 0;
}
The problem is quite trivial.
You have two containers (vector A and heap heap).
The heap contains copies of the data in the vector:
A.push_back(f); // copies f!
handle_type handle = heap.push(f); // copies f again!
You set the handle only on the copy in the heap:
(*handle).handle = handle; // store handle in the heap node only
Hence, in the temporary f and the vector A's elements, the value of handle is indeterminate (you just didn't give it any value).
Therefore when you do
heap.decrease(A[5].handle);
you invoke Undefined Behaviour because you depend on the value of A[5].handle, which is uninitialized.
Simpler, correct, example:
Live On Coliru
#include <boost/heap/fibonacci_heap.hpp>
#include <boost/tuple/tuple_comparison.hpp>
struct W {
int a;
int b;
W(int a, int b) : a(a), b(b) { }
boost::tuple<int const&, int const&> get_key() const { return boost::tie(a, b); }
void decr() { b?a:--a, b?--b:b; }
};
struct heap_data;
using Heap = boost::heap::fibonacci_heap<heap_data>;
struct heap_data
{
W payload;
Heap::handle_type handle;
heap_data(W w) : payload(w), handle() {}
bool operator<(heap_data const & rhs) const {
return payload.get_key() < rhs.payload.get_key();
}
};
#include <vector>
#include <iostream>
int main()
{
Heap heap;
std::vector<Heap::handle_type> handles;
for (int i = 0; i < 10; i++)
{
Heap::handle_type h = heap.push(W { i, i + 3 });
handles.push_back(h);
(*h).handle = h;
}
(*handles[5]).payload.decr();
heap.decrease(handles[5]);
}