I'm trying to remove trailing spaces however I keep getting a segmentation fault. Not too sure where I am accessing memory out of bounds but this is my code. Leading spaces works fine.
String is the input for the function.
//remove leading spaces
char* final = string;
while(isspace((unsigned char)final[0]))
final++;
//removing trailing spaces
//getting segmentation fault here
int length = strlen(final);
while(length > 0 && isspace((unsigned char)final[length-1]))
length--;
final[length-1] = '\0';
The string I tested was
char* word = " 1 2 Hello ";
printf("%s\n", removeSpaces(word));
When I comment out the trailing spaces, it works perfectly. I don't why the code is failing at the trailing spaces. I would really appreciate the help.