Hi, I am seeing some un-expected behaviour when copying structs in the
following toy-example.
------------------------------------------------------------------------------
#include <iostream>
struct A {
char name[ 20 ];
};
A bar() {
A a;
strncpy( a.name, "function string", sizeof( a.name ) - 1 );
std::cerr << "in function address " << std::hex << &( a.name ) <<
std::endl;
return a;
}
int main( ) {
A a1;
strncpy( a1.name, "foo", sizeof( a1.name ) - 1 );
A a2 = a1;
std::cerr << "local original " << std::hex << &(a1.name)
<< " " << a1.name << std::endl;
std::cerr << "local copy " << std::hex << &(a2.name)
<< " " << a2.name << std::endl;
A a3 = bar();
std::cerr << "local returned from function " << std::hex <<
&(a3.name)
<< " " << a3.name << std::endl;
A a4 = bar();
std::cerr << "local returned from function " << std::hex <<
&(a4.name)
<< " " << a4.name << std::endl;
}
------------------------------------------------------------------------------
with output
local original 0x7fefffb10 foo
local copy 0x7fefffaf0 foo
in function address 0x7fefffad0
local returned from function 0x7fefffad0 function string
in function address 0x7fefffab0
local returned from function 0x7fefffab0 function string
------------------------------------------------------------------------------
Basically when I copy locals in main, the address of the memory of
"name" is different, and streaming the name member indicates it was
copied correctly.
When I assign the return from the foo() function, the copy references
the same memory for its name field as did the one in the function. I
am using g++ 4.1.2, does anyone know if it has copy on write semantics
for arrays?
If I compile with g++ 4.0.1, I see what I was expecting, namely the
copy returned from the function references different memory than the
in-function local.
ie:
------------------------------------------------------------------------------
output of g++ 4.0.1
local original 0xbffffaac foo
local copy 0xbffffa98 foo
in function address 0xbffffa50
local returned from function 0xbffffa84 function string
in function address 0xbffffa50
local returned from function 0xbffffa70 function string
------------------------------------------------------------------------------
Can someone explain this to me? I ran a memory profiler and it didn't
pick up anything wrong. Is it correct to assume c++ will do deep
copies of array members within structs, and this weirdness is just g++
specific, but safe?
Thanks in advance
Dave
--
[ See http://www.gotw.ca/resources/clcm.htm
for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


|