HP C/iX Library Reference Manual (30026-90004)

336 Chapter5
HP C/iX Library Function Descriptions
strcpy
character early in the program. The first chr element is then successively set to the next
lowercase character in the for loop, and the resulting two-character string is concatenated
onto the end of the alphabet assembled so far in alpha. Note the use of strcpy() to
initialize alpha. Remember that C transforms one or more characters enclosed in double
quotation marks into a character pointer to those characters followed by a null character.
Thus, the strcpy() statement above copies the character 'a' followed by a null character
into alpha.
There are some things to be aware of when using strcpy(), strncpy(), strcat(), and
strncat(). These functions all modify string
s1
in some way, but none of them check for
overflow in that string. Therefore, be sure there is enough room in
s1
to hold the added or
copied characters plus a terminating null character. Also, be sure you use a character
array
for
s1
(not just a character pointer), especially when using strcat or strncat. This
is because an explicitly declared array can have sufficient memory allocated to it to contain
all of its elements, but a character pointer simply points to a single location in memory.
Concatenating a string to the end of a string contained in an array is guaranteed to work if
the array is large enough. However, concatenating a string to a string of characters
referenced by a simple character pointer is dangerous, because the concatenated
characters could overwrite data in memory. For example,
char array[100], *ptr = "abcdef";
strcat(array, ptr);
works fine, because you are guaranteed that 100 storage elements have been set aside for
the array. However,
char *ptr1 = "abcdef", *ptr2 = "ghijkl";
strcat(ptr1, ptr2);
will not work. Although C makes sure there is enough room for the initializing strings
("abcdef" and "ghijkl" in this example), there are no guarantees that there is enough room
to add characters to the end of one of these strings. Therefore, the last fragment could
easily overwrite valid data occurring after the string pointed to by ptr1.
Because string
s2
is not modified, you can use arrays or character pointers for this item
with no ill effects.
See Also
memmove(), strlen(), strcat(), strncat(), strncpy(), ANSI C 4.11.2.3, POSIX.1 8.1