C - I keep getting segmantation fault with strtok() -


i want make function takes char *, tokenizes strtok() , returns char ** arguements. keep getting segmentation fault error every time try execute.

#include <stdio.h> #include <stdlib.h> #include <string.h>    #define length  10  char ** boom(char * line, int * lng){     size_t size = strlen(line )+1;     int tksize = *lng;     const char d[2] = " ";       char a[size];     memcpy(a, line , size);      char ** tk = (char**) malloc(tksize*sizeof(char*));     int i=0;     char* token = strtok(a, d);     while(token!=null){         tk[i] = token;         i++;                 token = strtok(null, d);     }     return tk;  }  int main(void){      int i, lng = length;     char * string = "this beutiful message.\0";     char ** tk = boom(string , &lng);      (i=0; i<lng; i++){           printf("%s\n", tk[i]);           }      return 0; } 

i need return type of boom() char** haven't used return type of char * []. suspect it's the char** malloc.thanks help.

you let strtok operate on local variable char a[size], char* token = strtok(a, d) point memory allocated on stack. once function boom has finished, memory not valid more, , that's reason segfault.


Comments