I want to copy a struct content in memory via char* pc
the print it back but here I have an exception (reading violation)
struct af {
bool a;
uint8_t b;
uint16_t c;
};
int main() {
af t;
t.a = true;
t.b = 3;
t.c = 20;
char* pc = nullptr;
memcpy(&pc, &t, sizeof(t));
std::cout << "msg is " << pc << std::endl; // here the exception
return 0;
}
then I want to recover data from memory to another structure of same type.
I did af* tt = (af*)(pc);
then tried to access to tt->a
but always an exception.
CodePudding user response:
You need to allocate memory before you can copy something into it. Also, pc
is already the pointer, you need not take the address of it again. Moreover, the byte representation is very likely to contain non-printable characters. To see the actual effect the following copies from the buffer back to an af
and prints its members (note that a cast is needed to prevent std::cout
to interpret the uint8_t
as a character):
#include <iostream>
#include <cstring>
struct af {
bool a;
uint8_t b;
uint16_t c;
};
int main() {
af t;
t.a = true;
t.b = 3;
t.c = 20;
char pc[sizeof(af)];
std::memcpy(pc, &t, sizeof(t)); // array pc decays to pointer to first element
for (int i=0;i<sizeof(af); i){
std::cout << i << " " << pc[i] << "\n";
}
af t2;
std::memcpy(&t2, pc,sizeof(t));
std::cout << t2.a << " " << static_cast<unsigned>(t2.b) << " " << t2.c;
}
0
1
2
3
1 3 20
Note that I replaced the output of pc
with a loop that prints individual characters, because the binary representation might contain null terminators and pc
is not a null terminated string. If you want it to be a null-terminated string, it must be of size sizeof(af) 1
and have a terminating '\0'
.