Re: confused about copying strings



Angus wrote:
The sample code below simulates receiving a protocol message with a tlv structure - type/length/data_value.

I am confused about copying the actual data to a temp string.

Since you know in advance that you have sufficient storage to store the copy, use strcpy.

int dtype = *mybytes++;
int dsize = *mybytes++;
size_t size = dsize;
char *data = malloc(size);
if(data != NULL)
{
if(strlen(mybytes) < size)
{
strcpy(data, mybytes);

printf("%s\n", data);

/* when finished with data... */
free(data);
}
else
{
something's wrong - your mybytes string length indicator is too low.
}
}
else
{
handle the out-of-memory error
}

data points to the /first/ character of the string - strcpy can't change data's value because we only passed its value, not the object itself. But strcpy can certainly copy the string to it.

<snip>

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
"Usenet is a strange place" - dmr 29 July 1999
Sig line vacant - apply within
.



Relevant Pages

  • Re: Secure C programming
    ... So take the case of the string functions. ... my code uses strcpy to stuff it into a buffer. ... but efficiency in processing them. ...
    (comp.lang.c)
  • Re: Two Questions about "strlen", "strcat" and "strcpy"
    ... The reasoning is that unsigned values have a larger maximum value and ... incremental string concatenation is simplified ... fact calls to strlen, implicit or not, is the real performance ... People may write strcpy() in "hand coded assembly language" if they ...
    (comp.lang.c)
  • Re: when to use strncpy() ?
    ... >> It works because strncpy() returns the address of the dest argument. ... If the user runs this with parameter "1234567890", the buffer will ... If the strcpy were replaced by ... strcpyis completely safe to use /if/ you know that the string will ...
    (comp.lang.c)
  • Re: strcpy() - dangerous? [Was Re: gets() - dangerous?]
    ... strncpy is safer than strcpy and if I try to use ... /* str_size + 1 is based on strlen not including the terminating null in the size of the string. ... Why don't you use memmove which *does* exist because it is part of the C standard? ...
    (comp.lang.c)
  • Re: Dangerous convertion?
    ... strcpy() is safe only when you know that the length of the source ... destination does not require knowing the length of the source. ... if your destination buffer is a statically sized array and you ... don't intend to append data to your string, ...
    (comp.lang.c)