Search code examples
cstringwhitespacetrim

Segmentation fault when removing trailing whitespace from string in c


I am trying to remove the white spaces at the end of a string. I have the following code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

char *trim(char *str) {
   char *end;
   end = str + strlen(str) - 1;
   while(end > str && isspace((unsigned char)*end)) {
      end--;
   }
   *(end++) = '\0'; //this line causes the segfault
   return str;
}

int main(void) {
   char *str = "mystring  ";
   printf("before trim string is %s\n", str);
   printf("length before: %d\n", strlen(str)); //should be 10
   str = trim(str);
   printf("after trim string is %s\n", str);
   printf("length after: %d\n", strlen(str)); //should be 8
   return 0;
}

When I run the code, I get a segmentation fault. What I'm not sure about is why incrementing the pointer 'end' by 1, and then changing the value it points to from a white space to the null terminator causes the segfault. I have read that incrementing a pointer in C such that the pointer does not point to an element of an array is undefined behaviour. However, wouldn't the white spaces at the end of "mystring" still be part of the char array str[]? Any help is really appreciated.


Solution

  • The issue here is that the line causing the crash is attempting to modify a string literal, which results in undefined behavior.

    According to https://en.cppreference.com/w/c/language/string_literal ,

    String literals are not modifiable (and in fact may be placed in read-only memory such as .rodata). If a program attempts to modify the static array formed by a string literal, the behavior is undefined.

    You'll have to make sure to pass a char* to a modifiable array, such as one you allocate yourself with malloc().