'anything wrong with this trim() method in C
this method is for trimming a string in C by deleting spaces from the beginning and end. BTW iam not that good with C and actually facing some issues with dealding with strings
char* trim(char s[])
{
int i, j;
int size = strlen(s);
//index i will point to first char, while j will point to the last char
for(i = 0; s[i] == ' '; i++);
for(j = size - 1; s[j] == ' '; j--);
if(i > 0)
s[i - 1] = '\0';
if(j < size - 1)
s[j + 1] = '\0';
s = &s[i];
return s;
}
Solution 1:[1]
This loop
for(j = size - 1; s[j] == ' '; j--);
will access an out-of-bounds index when:
the input string consists entirely of spaces (e.g.,
" "
), in which case there is nothing stoppingj
from reaching-1
and beyond, orthe input string is the empty string (
""
), wherej
starts at-1
.
You need to guard against this in some way
for (j = size - 1; j >= 0 && s[j] == ' '; j--)
The other thing to consider is that you are both: modifying the contents of the original string buffer, and potentially returning an address that does not match the beginning of the buffer.
This is somewhat awkward, as the user must take care to keep the original value of s
, as its memory contains the trimmed string (and might be the base pointer for allocated memory), but can only safely access the trimmed string from the returned pointer.
Some things to consider:
- moving the trimmed string to the start of the original buffer.
- returning a new, dynamically allocated string.
Some people have warned that you cannot pass a string literal to this function, which is true, but passing a string literal to a non-const argument is a terrible idea, in general.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Oka |