0

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?

Mike Minaev
  • 1,912
  • 4
  • 23
  • 33
  • it's a completely new issue now better ask a new question with reference to this one (btw: it's because trim_whitespace() deosn't necessarily return the pointer allocated) – Ingo Leonhardt Aug 27 '14 at 11:24

1 Answers1

0

trim_whitespace("abc"); will try to modify a constant data.

"abc" is a constant and might be allocated in constant space (ie: a location in memory which is reserved for read only access).

Ferenc Deak
  • 34,348
  • 17
  • 99
  • 167