M
Martin Jensen
Hi
First of, I know that void* usually is a bad idea to use, but I still want
to figure out this problem.
I assign the adress of a value to the void* and tries to retrive it again.
When I try to cast it back to a string* and get the content, something
strange happens. See the comments in the code.
This is the stipped down version of the code. It compiles and runs.
#include <string>
#include <sstream>
#include <iostream>
using std::cout;
using std::endl;
using std:stringstream;
using std::string;
struct Variable {
void* value;
int type;
void setString(string s) {
value = &s;
// This prints out the memory adress of the value and it's content.
// This prints correctly.
cout << value << endl << *(string*)value << endl;
}
string getString() {
string* ret = (string*)value;
// This prints the same memory adress as above, but the content of the
value
// doesn't print correctly. The content is printed, but it doesn't seem
to stop
// what it encounters to \0. It just continues to write out content from
memory
// until it encounters segmentation fault.
cout << ret << endl << *ret << endl;
return *ret;
}
};
int main() {
Variable a;
a.setString("TEST");
string s = a.getString();
cout << s << endl;
return 0;
}
Thanks in advance
Martin Jensen
First of, I know that void* usually is a bad idea to use, but I still want
to figure out this problem.
I assign the adress of a value to the void* and tries to retrive it again.
When I try to cast it back to a string* and get the content, something
strange happens. See the comments in the code.
This is the stipped down version of the code. It compiles and runs.
#include <string>
#include <sstream>
#include <iostream>
using std::cout;
using std::endl;
using std:stringstream;
using std::string;
struct Variable {
void* value;
int type;
void setString(string s) {
value = &s;
// This prints out the memory adress of the value and it's content.
// This prints correctly.
cout << value << endl << *(string*)value << endl;
}
string getString() {
string* ret = (string*)value;
// This prints the same memory adress as above, but the content of the
value
// doesn't print correctly. The content is printed, but it doesn't seem
to stop
// what it encounters to \0. It just continues to write out content from
memory
// until it encounters segmentation fault.
cout << ret << endl << *ret << endl;
return *ret;
}
};
int main() {
Variable a;
a.setString("TEST");
string s = a.getString();
cout << s << endl;
return 0;
}
Thanks in advance
Martin Jensen