treatyoself
treatyoself

Reputation: 83

Remove Trailing Spaces in C

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.

Upvotes: 0

Views: 5950

Answers (1)

AlenL
AlenL

Reputation: 448

The string literal " 1 2 Hello " is stored in read-only memory. Copy it first before attempting to write '\0' into it, and the problem will go away. So e.g., just replace this:

char* final = string;

with this:

char* final = strdup(string);

Edit 1: Upon considering this in more detail, I realized you also do a leading trim before trailing trim. Since you are moving the pointer, the allocation needs to happen after the leading trim, or the caller will not be able to free the memory. Here's a complete solution that shouldn't have any errors:

char *removeSpaces(const char *string) {

    while(isspace((unsigned char)string[0]))
        string++;
    char *final = strdup(string);
    int length = strlen(final);
    while(length > 0 && isspace((unsigned char)final[length-1]))
        length--;
    final[length-1] = '\0';
    return final;
}

Edit 2: While I would not recommend it in this case, it might be useful to be aware that if the variable was declared like this:

char word[] = "  1 2 Hello    ";

It would have been in writable memory, and the problem would also not exist. Thanks to pmg for the idea.

The reason why it is not a good approach is that you are expecting the callers to the function to always provide writable strings, and that you will modify them. A function that returns a duplicate is a much better approach in general.

(Don't forget to free() the result afterwards!)

Upvotes: 1

Related Questions