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.
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