Article View: comp.std.c
Article #4678Re: memcpy
From: Mark Klenk
Date: Fri, 19 Jan 1996 16:10
Date: Fri, 19 Jan 1996 16:10
48 lines
1635 bytes
1635 bytes
Geoff Wong wrote:
>
>Can memcpy cope with very complex objects?
I think what you're asking is whether memcpy() will perform
what is called a "deep" copy. No, it will not. memcpy()
simply copies a block of memory (contiguous bytes) from one
location to another. If you use it to copy an object that
contains pointers, the copy of it will contain those same
pointers, not new pointers to copies of what the original
ones pointed to. This is called a "shallow" copy, and is
all that memcpy()/memmove() can do.
If you want to implement a deep copy, you'll have to write
the routine yourself, something like:
typedef struct {
int a, b;
char * bar;
} Foo;
Foo * FooClone(Foo const * original)
{
Foo * foo;
foo = (Foo *)malloc(sizeof(Foo));
if (NULL != foo) {
size_t size = strlen(original->bar) + 1;
foo->a = original->a;
foo->b = original->b;
foo->bar = (char *)malloc(size);
if (NULL == foo->bar) {
free(foo);
foo = NULL;
} else {
memcpy(foo->bar, original->bar, size);
}
}
return foo;
}
To sidetrack a little, this is what the copy constructor in
C++ is often used for.
---
mklenk@coronacorp.com (Mark Klenk)
Technical Details
Message-ID:
<4dofpn$fk9@unix.sri.com>Path:
arc1-ca.pugleaf.net!unix.sri.com!usenetReferences:
<4dn0gu$itc@mirv.unsw.edu.au>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!unix.sri.com!usenet From: mklenk@updike.sri.com (Mark Klenk) Newsgroups: comp.std.c Subject: Re: memcpy Date: 19 Jan 1996 16:10:31 GMT Organization: SRI International Message-ID: <4dofpn$fk9@unix.sri.com> References: <4dn0gu$itc@mirv.unsw.edu.au> Reply-To: mklenk@updike.sri.com NNTP-Posting-Host: 204.75.161.40