Ene Uran
Posting Virtuoso
1,830 posts since Aug 2005
Reputation Points: 676
Solved Threads: 255
Skill Endorsements: 7
> How to you handle tabs?
If you will notice, this is not a generic function, the way we have in Python, Ruby and other languages. You need to pass the character to be stripped. If you want to strip off tabs, pass the junk character to be '\t'.
~s.o.s~
Failure as a human
12,220 posts since Jun 2006
Reputation Points: 3,307
Solved Threads: 783
Skill Endorsements: 54
Attention: rtrim could modify memory outside string range
While you're correct, the bug report is unhelpful because you haven't specified when this would happen or suggested a fix. The problem stems from an unchecked decrement of original , which can drop below string if it's empty of contains nothing but junk characters.
If whatever memory prior to string also contains junk characters, the loop will continue and modify memory outside the bounds of the array. If memory prior to string doesn't contain junk characters, at least one element beyond the array will be accessed, which is still undefined behavior.
Trimming away the entire string is the special case that needs to be considered here, with awareness of three potential cases at original[0]:
-
original[0] is '\0': The string was empty, so nothing needs to be done. -
original[0] is junk : The string is trimmed to nothing and must end at original[0] . -
original[0] neither '\0' nor junk : The string must end after original[0] , as in the original algorithm.
Once the potential cases are discovered, it's a simple matter to account for them:
char *rtrim(char *string, char junk)
{
char *original = string + strlen(string);
while (original != string && *--original == junk)
;
if (*original != '\0')
original[*original == junk ? 0 : 1] = '\0';
return string;
}
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,483
Solved Threads: 1,407
Skill Endorsements: 53