0

Possible Duplicate:
strtok giving Segmentation Fault

I try to use strtok function to split string in many tokens but in this example it returns me a seg. fault error. Where i'm in wrong??

#include <stdio.h>
#include <string.h>

int main(int argc, char** argv){
    int i=0;
    char * string = "HI:HOW:ARE:YOU:?", *tmp;

    while(1){
        if(i==0) tmp=strtok(string,":");
        else tmp=strtok(NULL,":");
        if(tmp==NULL) break;
        printf("%s\n",tmp);
        i++;
    }
    return 1;
}
dreamcrash
  • 47,137
  • 25
  • 94
  • 117
Pietro Luciani
  • 247
  • 1
  • 4
  • 14
  • `strtok` modifies the string passed to it, and you're passing it a string literal. –  Nov 03 '12 at 11:44
  • Soooooo many dupes of this question. Also, please **do read the documentation** of the functions you're trying to use. –  Nov 03 '12 at 11:56

1 Answers1

3

Change

char * string = "HI:HOW:ARE:YOU:?"

for

char string [] = "HI:HOW:ARE:YOU:?"

With char string [] you have an array, and char * you have a pointer. When you declare an array, it will request space to allocate the size of your string. The char * string creates a pointer that points to a literal string.

The problem with char *string it is that the point should not be changed because string literals are typically stored in read-only memory, thus causing undefined behavior 33

( for more detail read this https://www.securecoding.cert.org/confluence/display/seccode/STR30-C.+Do+not+attempt+to+modify+string+literals )

Therefore, since with strtok the contents of the string is modified and broken into smaller strings (tokens) you got problems.

dreamcrash
  • 47,137
  • 25
  • 94
  • 117