Hi

This code, compiles fine but results in a segmentation fault and when I comment out the part which adds the null character then the segmentation fault doesn't appear and it removes whitespace from the beginning but not the end.

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

char *trim(char *s)
{
  char *end;

   while(isspace(*s)) 
     {
       s++;
     }

  if(*s == 0)  // All spaces?
    {
      return s;
    }
 
  end = s + strlen(s) - 1;
  while(end > s && isspace(*end))
    {
      end--;
    }
  // Write new null terminator
  //*(end+1) = 0;

  return s;
}


int main (int argc, char* argv[])
{

  char *s = "    Hello world                    ";
  s = trim(s);
  printf("%s", s);

  
}

Recommended Answers

All 3 Replies

I didn't look closely for bugs in your trim algorithm, but I did notice a problem in main at a glance. If you replace your main function with this one, does the error still occur?

int main(void)
{
    char s[] = "    Hello world                    ";

    printf(">%s<\n", trim(s));

    return 0;
}

Trying to modify a string literal is an extremely bad idea because it's likely to be stored in read-only memory.

Thanks, that worked! But how would I store that back into a text variable? as char *s = trim(s) doesn't work.

I didn't look closely for bugs in your trim algorithm, but I did notice a problem in main at a glance. If you replace your main function with this one, does the error still occur?

int main(void)
{
    char s[] = "    Hello world                    ";

    printf(">%s<\n", trim(s));

    return 0;
}

Trying to modify a string literal is an extremely bad idea because it's likely to be stored in read-only memory.

You're trying to copy a string, which means having enough space available for the destination. The simplest method is with an array and strcpy:

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

/* ... */

int main(void)
{
    char s[] = "    Hello world                    ";
    char dst[25];

    strcpy(dst, trim(s));
    printf(">%s<\n", dst);

    return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.