Question

I am trying to trim the end of a ANSI C string but it keeps seg faulting on the trim function.

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

void trim (char *s)
{
    int i;

    while (isspace (*s)) s++;   // skip left side white spaces
    for (i = strlen (s) - 1; (isspace (s[i])); i--) ;   // skip right side white spaces
    s[i + 1] = '\0';
    printf ("%s\n", s);
}

int main(void) {
    char *str = "Hello World     ";
    printf(trim(str));
}

I can't seem to figure out why. I've tried like 15 different trim functions they are all seg faulting.

Was it helpful?

Solution 3

In char* str = "Hello world ", the string "Hello World " is stored in the read only of the address space. Trying to modify the read only memory causes undefined behavior.

Instead use

char str[] = "Hello World ";

or

char *str = malloc(sizeof("Hello World    ")+1);
strcpy(str, "Hello World    ");

and then try trim functions...

For more info on how memory is allocated for variables, refer to https://stackoverflow.com/a/18479996/1323404

OTHER TIPS

The trim function is fine, there are two errors in main: 1. str is a string literal, which should be modified. 2. The call to printf is wrong, because trim doesn't return anything.

int main(void) {
    char str[] = "Hello World     ";
    trim(str);
    printf("%s\n", str);
}

You are trying to modify a string literal "Hello World" being pointed by str which leads to the seg fault.

In main make str an array:

char str[] = "Hello World     ";

or malloc it:

char *str = malloc(sizeof("Hello World     ")+1);

Although "Hello World " has type char [] but it is stored in a read only buffer. Check the output here. Also this printf(trim(str)); does not make sense, since you are not returning anything from the trim function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top