polslinux
polslinux

Reputation: 1779

segfault when freeing a pointer during string reversing in C

int main(int argc, char **argv){
    char *str = argv[1];
    size_t len = strlen(str);
    char *dst = calloc(len+1, sizeof(char));
    int i;
    for(i=len-1; i>=0; i--){
        memcpy(dst, str+i, 1);
        dst++;
    }
    *(++dst) = '\0';
    printf("%s\n", dst);
    free(dst);
    return 0;
}

Error checking omitted for more readability
I don't understand why i got a segfault with this message: "glibc free(): invalid pointer:"
I'm trying to write a small program that reverse a string using pointers but:
1) the last printf print nothing;
2) i got a segfault

Upvotes: 1

Views: 110

Answers (3)

Roee Gavirel
Roee Gavirel

Reputation: 19443

the problem is you are changing the pointer in the calculations.
try use a temp or original for that like:

int main(int argc, char **argv){
    char *str = argv[1];
    size_t len = strlen(str);
    char *dst = calloc(len+1, sizeof(char));
    char *origDst = dst;
    int i;
    for(i=len-1; i>=0; i--){
        memcpy(dst, str+i, 1);
        dst++;
    }
    *(dst) = '\0';
    printf("%s\n", origDst);
    free(origDst);
    return 0;
}

Upvotes: 3

Ganesh
Ganesh

Reputation: 5990

There are 2 points to be considered. One, is to make a copy of the original pointer allocated by calloc as shared by ouah already. Another point is to eliminate the increment of the pointer when NULL is stored i.e. *(++dst) = '\0'; should be *dst = '\0';. With these 2 changes, I am able to run your program without any issues.

Upvotes: 1

ouah
ouah

Reputation: 145899

You have:

   char *dst = calloc(len+1, sizeof(char));
   /* ... */
   *(++dst) = '\0';
   /* ... */
   free(dst);

You must free the pointer that was allocated by malloc / calloc. Here you modified it. Make a copy of it so you can free it after.

Upvotes: 9

Related Questions