Question regarding pointer manipulation

Hi, I was trying to modify a function designed to split a string onto multiple lines and indent it. This function was written by someone else and when I came to check the end of the code I found the following:

Now it appears to me that the code is attempting to look one character before the end of the string, then rewind back over any space characters found at the end of the string before adding a carriage return and a linefeed and returning the contents of the buffer.

What I don't understand is that if the while loop never evaluates to true it looks like the pointer gets increased again and the '\n' will be written over the '\0' and leave the string be left unterminated.

Is this correct? The reason I ask is that this code has been in use for a long time and I have never noticed any problems with strings passed to it!

Yep. If the string passed doesn't end in whitespace, you're screwed. Furthermore, if it ends in one whitespace, it will back up to the white space, place a \n there, move to the null, and place the \r there. Again, killing your null. So the only time this will ever work right, is if the string ends in two or more whitespace, excluding the null.

No, you shouldn't add the mentioned line before the return. You should instead completely rewrite this. Basicly you have to rethink this so that you can handle the two cases mentioned. It's very possible for a string to be passed as described, which simply won't have room for you to add the "'\n\r".

In this case I don't think I have to worry about the size of the string as all of the calls to the function pass a buffer that has a significant amount of overhead over the maximum string length that can be used within that buffer, to allow plenty of room for additional formating to be added.

I still cannot believe this has never caused a problem before as the buffer being passed is not padded in any way, I will fix this straight away.

Depending on how the buffer is initialized, it could be set to nulls in the first place, which means everything beyond the null at the end of the string is also null, so you don't have the problem. However, if the function is used with a buffer that's not fully initialized to nulls first, you will have the problem.

So, if you're sure the buffer will always have room, then sure, go ahead and add the null assignment right before the return.