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 stopping j
from reaching -1
and beyond, or
the input string is the empty string (""
), where j
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.