Bummer! Edited the answer. Not sure about the off-by-one though.
Say the string is str[] = "spp\0". n = strlen(str) is 3.
In the end, res would be 1 and 2 * res - n == -1.
Oh. Found it. It's because I wasn't using strlen and had been passing over the length of the buffer instead of the length of the string. Only my code had the off by 1.