Segmentation fault when free the variable after using strt_ok

Viewed 61

I have segmentation fault when executing this simple program (it is just a light version to reproduce the error).

//   gcc main.c -Wall -Wextra -Wpedantic
//   ./a.out

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h> // uint32_t

int main(){

    char* rest = (char*)malloc(128 * sizeof(char));
    char* token= (char*)malloc(128 * sizeof(char)); 
    strcpy(rest,"Something_else");
    token = strtok_r(rest, "_", &rest);
    printf("%s\n", token);
    free(token);
    free(rest);
    return 0;
}

The free of the variable token does not give any error. The free of the variable rest gives me always a segmentation fault every time I use the function strok_r. What is going on? Any suggestion? No warnings are prompt at compilation time.

Question:

How to re-write this simple code properly?

2 Answers

You only need memory for the sentence, token and rest are just pointers.

And using a while loop, you can see all the tokens:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h> // uint32_t

int main(){

    char* rest , *token;
    char* setence= malloc(128 * sizeof(char)); 

    strcpy(setence, "Some_thing_else");

    token = strtok_r(setence, "_", &rest);

    while (token) 
    {
        printf("%s\n", token);
        token = strtok_r(NULL, "_", &rest);          
    }

    free(setence);

    return 0;
}

Will give:

Some
thing
else

You should neither allocate nor free the variable 'rest'. strtok_r uses its third argument to store where it got to in the original string. So:

char* rest;
char* copy= (char*)malloc(128 * sizeof(char)); 
strcpy(copy,"Something_else");
char* token = strtok_r(copy, "_", &rest); 
// ...
free( copy);  // don't free token or rest
Related