Search code examples
csegmentation-faultmallocfree

Segmentation fault when free the variable after using strt_ok


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?


Solution

  • 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