Fix for overwriting a string with itself

The logic for replacing part of a string with itself without creating a
new allocation is very tricky. Detect if we're replacing the same string
and always reallocate if it would cause the size of the string to
change. Also, use memmove() in the case the string size is the same.