Q: HOW DO I... safely copy or concatenate overlapping strings?
A: The C standard library provides memmove() for safely copying overlapping memory areas, but no corresponding function for working specifically with character arrays (strings). This Snippet presents two functions which are analogs of the standard strcpy() and strcat() functions which may safely be used when string spaces overlap.
#include <string.h>
char *sstrcpy(char *to, char *from)
{
memmove(to, from, 1+strlen(from));
return to;
}
char *sstrcat(char *to, char *from)
{
sstrcpy(to + strlen(to), from);
return to;
}
More C Snippets
- Determining a file's size
- Rounding floating-point values
- Sorting an array of strings
- Computing the wind chill factor
- Timers and default actions
- Getting a string of arbitrary length
All the code in C Snippets is either public domain or freeware and may therefore freely be used by the C programming community without restrictions. In most cases, if the original author is someone other than myself he or she will be identified. Thanks to all who have contributed to this collection over the years. I hope Dr. Dobb's readers will find these useful.
--Bob Stout
rbs@snippets.org


