Hello,
I need some help with c++ objects instantiated into a shared memory segment.
I wrote a class that acts as an interface to the common (shared mem.) operations.
Everything works fine until I needed to copy a dynamically created array of structs that also contains subarrays of the same type and two integer members.
I created a clone function that receives origin and destination and uses memcpy to “clone” the whole structure.
Bellow I put some working code that behaves exactly like the original.
struct test2
{
int a;
};
struct test
{
int a;
int b;
test2 *c;
};
void Clone(test* from, void *destination)
{
memcpy (destination, from, sizeof(NodeInformation));
test *to = (test *) destination;
to->c = (test2 *) calloc(10 , sizeof(test2));
memcpy (to->c, from->c , 10 * sizeof(test));
}
The destination parameter is a pointer to a shared memory segment. The function should copy the origin content to the destination using struct test architecture.
The first line (of Clone()) works ok. I am able to see its content a the memory position.
Memory:
destination = 0xb7fde000
to = 0x08049460
to = 0xb7fde000
to.a = 123
to.b = 234
to.c = 0x08053170 // t.c = array of test2
As you can see to.c points to a local memory segment, not to a part of the shared memory as it should be.
What I want to achieve is to get to.c point to the righ direction but I don’t know how. I used calloc() to initialize to.c. Without this I get a segfault.
Main code
SharedMemory *sm1 = new SharedMemory(SHAMEM_ID, 1600, true);
void *pool = sm1->Get();
test *tp = (test *)pool;
test *t = new test;
t->a = 123;
t->b = 234;
t->c = (test2 *) malloc(sizeof(test2) * 10);
t->c[0].a = 777;
t->c[7].a = 888;
Clone(t, pool);
Both test.a and test.b field are copied correctly but the array always point to invalid places.
What am i doing wrong?
Thanks in advance.