Search code examples
cpointerscstringc-strings

C string strip whitespace throws a segmentation error (core dumped)


This is the code the linux kernel uses to strip leading and trailing whitespace on a string:

char *strstrip(char *s)
{
        size_t size;
        char *end;

        size = strlen(s);

        if (!size)
                return s;

        end = s + size - 1;
        while (end >= s && isspace(*end))
                end--;
        *(end + 1) = '\0';

        while (*s && isspace(*s))
                s++;

        return s;
}

Here I use it as such:

int main( void ){

    /* strip test*/
    char buffer2[60];
    char* testy2 = buffer2;
    testy2 = "       THING!      ";
    printf("The stripped string: \"%s\"\n",strstrip(testy2));
    return 0;
}

The program compiles fine but when executed it states:

Segmentation fault (core dumped)

Why is this happening?


Solution

  • testy2 = "       THING!      ";
    

    sets testy2 to point to a string literal. This may exist in read-only memory so can't be written to by strstrip.

    You need to either allocate memory for testy2

    const char* s = "       THING!      ";
    testy2 = malloc(strlen(s)+1);
    strcpy(testy2, s);
    ....
    free(testy2);
    

    or, easier, just initialise buffer2 with the string you want to manipulate

    char buffer2[] = "       THING!      ";
    printf("The stripped string: \"%s\"\n",strstrip(buffer2