c - Seg fault occurs when copying char pointer into array of char pointers -


i reading in line of text file, , trying split on spaces strtok(), storing each token in array of char pointers using strcpy(), within function called tokenize.

code:

/** ** tokenizes contents of buffer words ** delimiter space character */ void tokenize(char *buffer, char *tokens[]){     char *token = null;     int = 0;     token = strtok(buffer, " ");     while(token != null){         strcpy(tokens[i], token);//seg fault line         token = strtok(null, " ");         i++;     } } 

i assumed, based on function description in k&r, call work because passed char pointer, tokens[i] should dereference to, , char pointer containing memory address of string copied, token should be. however, seg fault when try strcpy.

this function called in main after line retrieved using call fgets(). buffer declared char buffer[maxline_len - 1] gives size of 100. tokens declared char *tokens[maxline_len - 1].

call tokenize in main:

while(fgets(buffer, maxline_len, inputfile)){     int choice;     printf("%s", buffer);     tokenize(buffer, tokens);     /**     ....     */ } 

i using: gcc (ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609

edit: declaration of tokens (this occurs before while-loop shown above, , in main):

char *tokens[maxline_len - 1];//maxline_len - 1 = 100  int a; for(a = 0; < maxline_len - 1; a++)     tokens[a] = null; 

there 4 possibilities can think of

  1. tokens null or uninitialised
  2. tokens initialised haven't allocated enough space. if allocate space 4 tokens strtok() parses 5 tokens?
  3. the individual elements of tokens nnull or uninitialised
  4. you didn't allocate enough space in each elemant copy token string.

one or more of applies code. 1 way fix allocate tokens inside function , return in pointer (with count return value).

enum {     chunk_size = 16; // trick int constant in c works everywhere #define works };  size_t tokenize(char *buffer, char **tokenret[]) {     size_t capacity = 0;     char** tokens = null;     size_t count = 0;     char *token = null;     token = strtok(buffer, " ");     while(token != null)     {         count++;         if (count > capacity)         {             capacity += chunk_size;             tokens = realloc(tokens, capacity * sizeof *tokens);         }         tokens[count - 1] = strdup(token);//strdup mallocs space , copies string         token = strtok(null, " ");     }     *tokenret = tokens;     return count; } 

call this

char** mytokens = null; size_t tokencount = tokenize(buffer, &mytokens); 

then tidy @ end, free() first tokencount elements of mytokens , free mytokens.


Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -