Search code examples
c++memcpy

memcpy in C++ doesn't copy u_int32_t to unsigned char*


I'm with a problem when using memcpy function.

I need to create an array of unsigned char with three parts: id, size of data array, data array. But I couldn't do nor the first part yet.

#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <vector>
#include <string>

int main() {    
    u_int32_t OID;
    unsigned char *serialized;
    
    OID = (u_int32_t)5;
    
    serialized = new unsigned char[sizeof(u_int32_t)];
    
    memcpy(serialized, &OID, sizeof(u_int32_t));
    
    std::cout << "After inserting OID: <" << serialized << ">\n";
    
    memcpy(serialized, "test", sizeof(u_int32_t));
    
    std::cout << "After inserting \'test\': <" << serialized << ">\n";

}

The output this code generates is:

    After inserting OID: <> 
    After inserting 'test': <test>

I can't understand why, in the first case, memcpy doesn't copy OID to serialized and in the second case it copies the string test correctly.

It would be great if you could help me.

Thank you in advance.

Solution

I was trying to get number 5 when printing serialized. But it is not correct. The most adequate is to do something like this:

u_int32_t answer;
memcpy(&answer, serialized, sizeof(u_int32_t));
std::cout << "Answer: <" << answer << ">\n";

Thanks for answers and comments!


Solution

  • 5 in ASCII is not printable since it's a control character. ASCII Table

    You can try below and it will print a as expected.

    OID = (u_int32_t)'a';