First of all, I am using C++ and I am a newbie on it. I have an interface with exposes a method unsigned char * readRequest()
. All of my classes inherit this interface and implement the unsigned char * readRequest()
in its way (dealing with float, string, int, double, char), but return unsigned char *
. Below are some of my implementations of readRequest()
that converts float to unsigned char *
.
Edited: I am returning a pointer to a local variable and this is an undefined behavior. How do I return the real value in C++?
unsigned char * readRequest() {
float preCent = distanceCentimeters();
std::cout << preCent << std::endl; // print correct result
unsigned char buf[4];
memcpy(buf, &preCent, sizeof(preCent));
float result;
memcpy(&result, buf, sizeof(result));
std::cout << result << std::endl; // print correct result
return buf;
}
int main(void) {
unsigned char *readRequestArray;
readRequestArray = (unsigned char*) readRequest();
float converted_back;
memcpy(&converted_back, readRequestArray, sizeof converted_back);
std::cout << converted_back; // ERROR due to return a pointer to local variable
}
Output and error:
24.2882
jN�A
Segmentation fault