Click to See Complete Forum and Search --> : memcpy
crokett
06-04-2002, 05:24 PM
With the following code:
{CODE]memcpy(*server.name, "12345", 5)[/CODE]
After the copy will server.name be 5 bytes or will it be 5 bytes+a6th null-terminated byte?
thanks
binaryDigit
06-04-2002, 09:44 PM
MEMCPY(3) Linux Programmer's Manual MEMCPY(3)
NAME
memcpy - copy memory area
SYNOPSIS
#include <string.h>
void *memcpy(void *dest, const void *src, size_t n);
DESCRIPTION
The memcpy() function copies n bytes from memory area src
to memory area dest. The memory areas may not overlap.
Use memmove(3) if the memory areas do overlap.
so my guess would be no it doesn't. it will be 5 bytes
debiandude
06-04-2002, 11:04 PM
"12345" is 6 bytes long. When you put thing in a string C automatically appends a null. You need to copy 6 bytes if you want a null.
for instance:
int main(void)
{
char one[5], two[5];
int i;
memcpy(one, "12345", 5);
memcpy(two, "12345", 6);
for(i = 0; *(one+i); i++) {
printf("%x", *(one+i));
}
puts("|\n");
for(i = 0; *(two+i); i++) {
print("%d", *(two+i));
}
puts("\n");
return 0;
}
Notice how the second one stop at 5 becuase it hits a null, and the first one dosn't.
[ 04 June 2002: Message edited by: debiandude ]
jemfinch
06-05-2002, 01:24 AM
Don't use memcpy, its behavior is undefined in the case of an overlapping source and destination. Use memmove instead.
Jeremy
bwkaz
06-07-2002, 01:55 PM
Perhaps, but if you've malloc'ed correctly, the areas can't overlap ;)
jemfinch
06-08-2002, 01:51 PM
Originally posted by bwkaz:
<STRONG>Perhaps, but if you've malloc'ed correctly, the areas can't overlap ;)</STRONG>
Not necessarily. That's certainly not an invariant, perhaps when you're working with late copying of substrings.
Using memmove instead of memcpy is just good programming practice. Anytime you see "undefined behavior" in a C definition, you should run screaming.
Jeremy
bwkaz
06-10-2002, 01:12 PM
Originally posted by jemfinch:
<STRONG>Not necessarily. That's certainly not an invariant, perhaps when you're working with late copying of substrings.</STRONG>
Err... ok... I'll just sort of take your word for that one.
(What is "late copying of substrings", anyway -- do you have any examples? Not necessarily that do overlap, but that just illustrate what you're talking about... I can take a guess about what you're talking about, just from the wording, but the "late" part is losing me.)
I was just assuming that if you called malloc() twice, the two regions could not overlap (because malloc marks the first as used and will not reallocate it the second time). Is this not a correct assumption? :eek:
<STRONG>Using memmove instead of memcpy is just good programming practice. Anytime you see "undefined behavior" in a C definition, you should run screaming.</STRONG>
Oh, yeah, I suppose that makes perfect sense. You should indeed run screaming ;)