How do I get the value of this void* back? - c++

I have a void pointer of which I can set the value just fine (at least I think I did it right). But when I try to get the value of what is stored there, all I get nothing back. Doesn't matter if the void* points to a string or int or anything else.
What am I missing here?
class Vertex2{
public:
int _id;
void *_data;
template<typename T>
T getData() {
T *value = (T*)_data;
return *value;
}
template <typename T>
void setData(T data) {
_data = &data;
}
};

void setData(T data) receives data by value.
Setting a pointer to data therefore is only valid for the lifetime of that function call.
After that, the pointer dangles, and dereference behaviour is undefined.

template <typename T>
void setData(T data) {
_data = &data;
}
let's check what's going on here. You store a pointer to a local variable (method argument actually). Right after you leave the method the local var is destroyed and its memory is free to be reused. Now your void* points to the same memory address but the memory can contain anything.

Try it like this:
// the entire class should be templated and you should not cast the data to void
template<typename T>
class Vertex2
{
public:
int _id;
// data is no longer void
T m_data;
// now returning a const pointer to your data and protect it against manipulation from outside
getData() const {
return m_data;
}
// was setting the address of a temporary, that will not work. Now it takes a copy and moves that to the member.
void setData(T data) {
m_data = std::move(data);
}
};
I have added comments in the code.
As to your code
template <typename T>
void setData(T data) {
_data = &data;
}
Do not do that. You store the address to the temporary copy of data. This will go wrong!
void *_data;
Do not store the data as void, template the class like this:
template<typename T>
class Vertex2
{
T m_data;
.
.
.

There's nothing stored there.
You set the pointer to point to a function argument, that then went out of scope.
You can cast as much as you like, but that object has gone!
This design won't work unless you dynamically allocate.
Consider a std::variant or something instead.

Related

WriteProcessMemory std::vector<any> custom any class

How would i use Write Process Memory with a std::vector
This works if i use std::vector
Im not sure if this any class is returning right info when using .Data()
class any
{
private:
struct base {
virtual ~base() {}
virtual base* clone() const = 0;
};
template <typename T>
struct data : base {
data(T const& value) : value_(value) {}
base* clone() const { return new data<T>(*this); }
T value_;
};
base* ptr_;
public:
template <typename T> any(T const& value) : ptr_(new data<T>(value)) {}
any(any const& other) : ptr_(other.ptr_->clone()) {}
any& operator= (any const& other) {
any(other).swap(*this);
return *this;
}
~any() { delete this->ptr_; }
void swap(any& other) { std::swap(this->ptr_, other.ptr_); }
template <typename T>
T& get() {
return dynamic_cast<data<T>&>(*this->ptr_).value_;
}
};
template<typename T>
size_t vectorsizeof(const typename std::vector<T>& vec)
{
return sizeof(T) * vec.size();
}
std::vector<any> args{100, 1.1f};
WriteProcessMemory(hProc, pMemory, args.data(), vectorsizeof(args), nullptr)
There has to be a easy way to use std::any in a vector with Write Process Memory.
No, there does not.
Ignoring what std::any does with the value it stores for the moment, std::any stores its value (as if) indirectly. This means that it is rather like a vector<T>; it stores a pointer to the object which it allocated on the heap (except the T is hidden from the type and it only stores one of them). So copying the bits of the any itself will not (necessarily) make the T it stores visible; you are (may be) copying a pointer, not what it points to.
Furthermore, any can't be delivered across processes like this, for many reasons. Even if you could get access to the byte-range of the object being stored by an any, you wouldn't be able to use that to reconstruct the any on the other side. And even if you somehow could, you'd somehow have to transmit the type_index that represents the type stored in the any. And that isn't cross-process compatible; a type index value for a particular type in one process can be different from the index for the same type in the other process.
What you want simply isn't going to work. You'll have to use something else, and that something else is going to have to have some knowledge of the type of data it's transmitting.

Const correctness in struct initialization

I'm playing with C++ and const-correctness right now.
Assume you have the following structure
template <typename T>
struct important_structure {
public:
T* data;
int a;
important_structure(const T& el, int a);
void change();
};
template <typename T>
void important_structure<T>::change() {
//alter data field in some way
}
template <typename T>
important_structure <T>::important_structure(const T& el, int a) : data(&el), a(a) //error line {
};
int main() {
important_structure<int>* s = new important_structure<int>{5, 3};
}
When compiling with std=c++11, the compiler returns the following error:
invalid conversion from ‘const int*’ to ‘int*’
Now, I know it's unsafe to cast a const int* to int*. The problem is that I have a data structure and I don't want to put the field data as a constant.
However, I don't want to remove the const qualifier in the constructor since, I think, it's informative for future developers: it clearly says that el won't be modified by the function. Still the field data may be modified by some other function in important_structure.
My question is: How can I deal with fields which are initialized in the costructor and altered in some other function?
Most of const correctness deals with simple answers, but no question (I think) deals with scenarios where a const parameter is passed to a data structure and then such data structure is altered by someone else.
Thanks for any kind reply
passing el as a const reference doesn't just mean the function will not change el during the run of the function, it means because of this function call, el won't be changed at all. And by putting the address of el into non-const data, you violate that promise.
So, the clean solution, if you indeed want to change data, is removing the const. since it is not informative to future developers, but misleading. Casting away the const would be very bad here.
Let's use a simple class as T type of important_struct:
class Data
{
public:
Data() : something(0){}
Data(int i) : something(i){}
Data(const Data & d) : something(d.something){}
//non-const method: something can be modified
void changeSomething(int s){ something += s; }
//const method: something is read-only
int readSomething() const { return something; }
private:
int something;
};
This class has a very simple, yet well encapsulated, status, i.e. the int something field, which is accessed through methods in a very controlled way.
Let (a simplified version of) important_structure hold an instance of Data as a private field:
template <typename T>
struct important_structure
{
public:
important_structure(T * el);
void change();
int read() const;
private:
T* data;
};
We can assign a Data instance to an important_structure instance this way:
important_structure<Data> s(new Data());
The instance is assigned in construction:
template <typename T>
important_structure <T>::important_structure(T * el) : data(el) {}
Now the great question: do important_structure take ownership of the Data instances it holds? The answer must be made clear in documentation.
If it is yes, important_structure must take care of memory cleanup, e.g. a destructor like this one is required:
template<typename T>
important_structure<T>::~important_structure()
{
delete data;
}
Notice that, in this case:
Data * p = new Data()
// ...
important_structure<Data> s(p);
//p is left around ...
another pointer to the Data istance is left around. What if someone mistakenly call delete on it? Or, even worse:
Data d;
// ...
important_structure<Data> s(&p); //ouch
A much better design would let important_structure own its own Data instance :
template <typename T>
struct important_structure
{
public:
important_structure();
void change();
// etc ...
private:
T data; //the instance
};
but this is maybe simplistic or just unwanted.
One could let important_structure copy the instance it will own:
template<typename T>
important_structure<T>::important_structure(const T &el)
{
data = el;
}
the latter being the constructor provided in the question: the object passed won't be touched, but copied. Obviously, there are two identical Data objects around, now. Again, the result could not be what we needed in the first place.
There is a third way, in the middle: the object is instantiated outside the owner, and moved to it, using move semantics.
As an example, let's give Data a move assignment operator:
Data & operator=(Data && d)
{
this->something = d.something;
d.something = 0;
return *this;
}
and let important_structure provide a constructor which accepts an rvalue reference of T:
important_structure(T && el)
{
data = std::move(el);
}
One can still pass a Data instance using a temporary as the required rvalue:
important_structure<Data> s(Data(42));
or an existing one, providing the required reference from an lvalue, thanks to std::move:
Data d(42);
// ...
important_structure<Data> x(std::move(d));
std::cout << "X: " << x.read() << std::endl;
std::cout << "D: " << d.readSomething() << std::endl;
In this second example, the copy held by important_structure is considered the good one while the other is left in a valid but unspecified state, just to follow the standard library habits.
This pattern is, IMHO, more clearly stated right in code, expecially if considered that this code will not compile:
Data d(42);
important_structure<Data> x (d);
Whoever wants an instance of important_structure must provide a temporary Data instance or explicitly move an existing one with std::move.
Now, let the important_structure class be a container, as you asked in comment, so that data is somehow accessible from outside. Let's give a method like this to the important_structure class:
const T & owneddata() { return data; }
Now, we can use data const methods like this:
important_structure<Data> s(Data(42));
std::cout << s.owneddata().readSomething() << std::endl;
but calls to `Data' non-const methods will not compile:
s.owneddata().changeSomething(1000); //not compiling ...
If in need of it (hope not), expose a non-const reference:
T & writablereference() { return data; }
Now the data field is at full disposal:
s.writablereference().changeSomething(1000); //non-const method called
std::cout << s.owneddata().readSomething() << std::endl;
Using const T& el and data(&el) is a really bad idea, because it implies that you could write:
new important_structure<int>{5, 3};
But to write new important_structure<int>{5, 3}; would result in data holding an address that would no longer be valid immediately after calling the constructor.
If you want that the point data can be changed, but that the value where the pointer points to cannot be changed, then you want to write it that way:
template <typename T>
struct important_structure {
public:
T const * data;
int a;
important_structure(T const * el, int a);
void change();
};
template <typename T>
void important_structure<T>::change() {
//alter data field in some way
}
template <typename T>
important_structure <T>::important_structure( T const * el, int a) : data(el), a(a) { //error line
};
int main() {
int i = 5;
important_structure<int>* s = new important_structure<int>{&i, 3};
}

How to pass data to a templated collection

I have to write a generic data structure that resembles a C++ vector as part of an assignment.
This is my idea for the Vector:
template<typename T>
class MyVector {
private:
T* data_;
size_t size_;
public:
MyVector();
MyVector(const MyVector &otherVector);
// which one should I use?
add(const T& value);
add(T value);
~MyVector();
};
Now I wonder how to pass values to the methods. Coming from Java I am a bit overwhelmed. In Java you wouldn't hesitate and pass the value by reference, the GC would never delete the object if it is still referenced.
In C++ you would create a mess if you would pass by reference considering code like this:
void myFunction(MyVector &myVector) {
int a = 5;
myVector.add(a);
}
int main() {
auto vector = MyVector<int>();
myFunction(vector);
// now the vector contains a reference to
// something that doesn't exist anymore.
}
How do you solve this problem? Would you just pass by reference and create a copy or do you pass by value (which creates a copy for you)
Looking at the C++ std::vector interface I see that they use references.
I just don't see the value of passing by reference if you have to create your own copy.
add(const T& value) is ok, you just should be sure that there is properly defined assign operator for T. So, the implementation will be:
void Add(const T& value) {
if (m_size == m_maxSize) realloc(); // stuff to have enough space
m_data[m_size++] = value; // here copy is creating
}
default impl of assign operator just byte-copy fields of class, it is not always correct.
Other solution, if you want more java-style semantic, is to make T = shared_ptr<YourType> or T = YourType*
The latter is rather difficult because require skill of manual lifetime control, so is undesirable for c++ beginners.
void myFunction(MyVector<shared_ptr<X>> & myVector)
{
shared_ptr<X> x(new X(...));
myVector.add(x);
}
works similar to references in Java.
Other way, that was used in old times:
template<typename T>
class MyVector {
private:
T** data_; // now you have array of pointers, so should be careful
....
add(T* value);
....
}
void myFunction(MyVector<X> & myVector)
{
X * x = new X(...);
myVector.add(x); // now x belongs to myVector and it should handle its lifetime
}

C++ operator->() overload

Okay, since it's my first question, let me try again. I edited post and changed code to make it easier for you all to understand.
template <typename T>
class Structure
{
protected:
DWORD64 _instanceAddress;
T _structPointer;
public:
Structure<T>(DWORD64 instanceAddress);
~Structure();
T* operator->();
};
template <typename T>
T* Structure<T>::operator->()
{
Driver::ReadMemory( _instanceAddress, sizeof(T), &_structPointer );
return static_cast<T*>( &_structPointer );
}
struct C
{
int some_value;
}
struct B
{
C *pointer_to_C;
}
struct A
{
B *pointer_to_B;
}
//CODE
Structure<A> myStructure(DWORD64 AddressInMemory);
myStructure->pointer_to_B->pointer_to_C->some_value;
I'm reading other process memory through driver. Address of structure I'm trying to reach is static, so there is nothing to worry about. Is there any way that I can change my memory reading class to make it work like I've specified in bottom line of code? The ideal situation would be to do some changes in operator->() overload to do some checks regarding type user is trying to reach.
It should allow to define only lowest Structure in pointer chain and then just dereference it like its being done normally on mother-process raw memory.
So I'm imagining it would be something like that:
template <typename T>
T* Structure<T>::operator->(type_of_desired_variable var_name)
check if var_name is int or float
if not then define new Structure<type_of_desired_variable> and store it somewhere, then call its operator->()

C++ Access violation reading location

I am trying to make a basic any style class in C++, called object. It compiles successfully, but before anything happens, I get the error: Unhandled exception at 0x008128C1 in object.exe: 0xC0000005: Access violation reading location 0xCCCCCCCC.:
#include <typeinfo>
struct object
{
public:
template < typename T > struct Data
{
public:
Data(T value) : val_(&value){}
Data() : val_(nullptr){}
T* value()
{
return val_;
}
~Data()
{
delete &val_;
}
template < typename Tn > void Swap(Data<Tn>* D)
{
if (std::is_destructible<T>())
{
val_->~T();
}
Tn n_val = (Tn)val_;
std::swap<Tn>(&n_val, D->value());
}
private:
T* val_;
};
struct Inner : Data<void*>
{
template < typename T > void Cast()
{
Swap<T>(new Data<T>((T)NULL));
}
template < typename T > void Cast(const T& value)
{
Swap<T>(new Data<T>(value));
}
};
private:
Inner* Held;
public:
template < typename T > object(const T& value)
{
Held->Cast<T>(value);
}
template < typename T > void operator=(const T& value)
{
Held->Cast<T>(value);
}
template < typename T > void cast()
{
Held->Cast<T>();
}
template < typename T > void cast(const T& value)
{
Held->Cast<T>(value);
}
~object(){ delete Held; }
const void* operator()() const
{
return *Held->value();
}
};
And then in my test file
#include <iostream>
int main()
{
object MyObject = 5;
std::cout << MyObject();
}
Notice that you are doing delete Held; even though you never usednew. You never actually assign anything to Held, so it is uninitialized when you attempt to do Held->Cast<T>(value);. You're going to have to allocate a Held object in some way before you can do that.
You also have a problem your Data struct. Its constructor takes a copy of its argument, and then you store a pointer to that copy. That copy is local to the constructor though and will be destroyed when the constructor ends. The val_ pointer is left pointing at the destroyed object. Not only that, but you then do delete &val_; which attempts to deallocate the object that had automatic storage duration.
You really shouldn't be using new and delete as much as you are, and you would avoid many of the problems you're having.
Your object class is expecting data that has been allocated on the heap. This can be seen since you are accessing that data via a pointer in your object class, swapping its value, and deleting that pointer.
In your main function you are building an object with a literal value of 5. This value has not been allocated on the heap because no allocation was called for (no call to new exists). 5 may have been allocated on the stack, but as a literal it might also be stored in program ROM by the compiler, or any other location where it is dangerous to access the memory address.
The moment your code attempts to modify the data at the address of the literal value 5, you have committed an access violation because you are accessing memory that you are not allowed by your program to modify directly.
To solve this you probably want your object class to allocate a copy of the data being passed to it on the heap that it can then take ownership of and modify and delete at will.