Hello i have such code(found here, on stackoverflow)
char *trim_whitespace(char *string)
{
char *str;
str = (char *) malloc(strlen(string) + 1);
memcpy(str, string, strlen(string));
printf("%d\n", strlen(str));
char *end;
if (str == NULL) {
return NULL;
}
// Trim leading space
while(isspace(*str)) str++;
if(*str == '\0') // All spaces?
return str;
// Trim trailing space
end = str + strlen(str) - 1;
while(end > str && isspace(*end)) end--;
// Write new null terminator
*(end+1) = '\0';
return str;
}
and in main
int main(int argc, char **argv){
char *t;
t = trim_whitespace(argv[1]);;
printf(";%s;\n",t);
free(t);
}
but now it fails with
*** Error in `./a.out': free(): invalid pointer: 0x00000000020dd014 ***
Aborted (core dumped)
If i run
trim_whitespace(argv[1]);
everythink goes ok, i have result, that i want, it return trimmed string, but if i run such code
trim_whitespace("abc");
it would failed with segfault on line with
*(end+1) = '\0';
Please help me with my problem. Thank you. P.S. this function called from many places, is it possible to change smth inside trim_whitespace?