1

I have the following struct:

typedef struct{
    int test;
    std::string name;
} test_struct;

Then, I have the following code in the main function:

int main(int argc, char *argv[]){
    test_struct tstruct;
    tstruct.test = 1;
    tstruct.name = "asdfasdf";

    char *testout;
    int len;

    testout = new char[sizeof(test_struct)];

    memcpy(testout, &tstruct, sizeof(test_struct) );
    std::cout<< testout;
}

However, nothing gets printed. What's wrong?

1
  • Try NULL-terminating the string and adding a newline. Commented Apr 17, 2014 at 3:14

2 Answers 2

1

sizeof(std::string) yeilds same value always. It will not give you the runtime length of the string. To serialize using memcpy, either change the struct to contain char arrray such as char buffer[20] or compute the size of the required serialized buffer by defining a method on the struct which gives the runtime length of the bytes. If you want to use members like std::string, you need to go through each member of the struct and serialize.

memcpy(testout, (void *)&tstruct.test,  sizeof(int) );
memcpy(testout+sizeof(int), tstruct.name.c_str(),tstruct.name.length() );

memcpy against the entire struct will not work in such scenarios.

Sign up to request clarification or add additional context in comments.

2 Comments

yes i know the output won't be useful but i still wanted to get at least something. i tried memcpy-ing the values separately (per above), but still it doesn't print anything...
@Mariska: What you are doing is lying to the compiler and it won't work. The std::cout << testout; line assumes that testout points to a null-terminated string of printable characters. It doesn't and you should research how actual serialization is done.
0

Try NULL-terminating the string and also emitting a newline:

testout = new char[sizeof(test_struct) + 1];

memcpy(testout, &tstruct, sizeof(test_struct));
testout[sizeof(test_struct)] = '\0';
std::cout<< testout << std::endl;

However, as user3543576 points out, the serialization you get from this process won't be too useful, as it will contain a memory address of a character buffer, and not the actual string itself.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.