Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this work? copying anything into an array of bytes (chars)

Tags:

c++

c

memory

struct MyRect
{
    int x, y, cx, cy;
    char name[100];
};

int main()
{
    MyRect mr;
    mr.x = 100;
    mr.y = 150;
    mr.cx = 600;
    mr.cy = 50;
    strcpy(mr.name, "Rectangle1");

    MyRect* ptr;

    {
        unsigned char bytes[256];

        memcpy(bytes, &mr, 256);

        ptr = (MyRect*)bytes;
    }

    printf("X = %d\nY = %d\nCX = %d\nCY = %d\nNAME = %s\n", 
        ptr->x, ptr->y, ptr->cx, ptr->cy, ptr->name);

    return 0;
}

I was just testing how to put a struct/class in an array of bytes, and was suprised when it compiled and worked, the printf prints all the values which i set in the mr variable.

just a little confused to what exactly "ptr" is pointing to? has it allocated memory for ptr somewhere?

like image 841
Kaije Avatar asked Dec 05 '25 15:12

Kaije


1 Answers

It works by pure chance.

Firstly, you're basically making a byte-by-byte copy of the struct and placing it in a stack-allocated buffer using memcpy. However, you shouldn't do this in practice. It happened to work this time, because your struct is a POD (plain-old-data or C-struct), but if your struct was a C++ object with constructors/copy-constructors or what have you, you may have gotten a nasty surprise.

Secondly, the stack-allocated buffer containing the struct goes out of scope by the time you use it via your pointer, so what you're doing is totally undefined behavior. It only works by pure chance, and is not guaranteed to work again on a different computer or with a different compiler, or even at a different time of day.

like image 65
Charles Salvia Avatar answered Dec 07 '25 05:12

Charles Salvia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!