Memory managment

Hey there! Im curious a bit about placement some struct in memory.
The question is next:

Does it safe ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
struct A
{
    int a, b;
};
struct B
{
    int a;
};

void main ()
{
    A *a = new A;
    B *b = new B;

    a->a = 5;

    memcpy (b, a, sizeof B);
    cout << b->a << endl;     //5

    delete a; a = new A;

    memcpy (a, b, sizeof B);
    cout << a->a << endl;     //5
}


I would realy appreciate some useful reference.
Thx in advance.
1. Why do you declare the structure B, as long as it holds only one integer ?
1
2
3
4
struct B
{
    int a;
};


2. The correct function call is sizeof(B);.

3. I guess it is safe. As long as you delete the structures after using them, there shouldn't be any problems (that means you should have a delete b; somewhere at the end).
Last edited on
It`s only example, point is in that i want transform larger struct to smaler and back and worrying about lossing value of 'a'.

2. sizeof without brackets works too. At least in VS 2010.

3. Sure, and delete a; too ;)

there shouldn't be any problems

Yes, I think so too, but not assured.
Assuming you fix all compile errors and plug all memory leaks, this is indeed safe, but it's very much borderline.

The key rule here is that a pointer to the object of any standard-layout type can be reinterpret_cast to pointer to its first element (in other words, both leading padding and member reordering are prohibited in standard-layout types)

So, when memcpy() performs reinterpret_cast<unsigned char*>(b) and reinterpret_cast<unsigned char*>(a) (which is what it does before copying), it is the same as reinterpret_cast<unsigned char*>(&b->a) and reinterpret_cast<unsigned char*>(&a->a), so it will, indeed, safely copy a->a into b->a.

Topic archived. No new replies allowed.