tags:

views:

144

answers:

4

Hi, I have struct with this definition:

typedef struct gRow{
    char *txt;
    char *fileName;
    int line;
} gRow;

and i want to use strtok on the txt string. so, in some function that has gRow *row, i do this:

strtok(row->txt, SEPERATOR_CHARACTERS);

and this is the point where i get Segmentation Fault. if i replace it with:

strtok(strdup(row->txt), SEPERATOR_CHARACTERS);

it works just fine. any ideas why?

Thanks.

Shahar.

+1  A: 

You need to allocate the memory for gRow *row ; Then it will work fine, I hope.

pavun_cool
I did allocate... the code here is from function that get the pointer after everything already allocated.
+3  A: 

Note that strtok modifies the string - if your txt pointer is pointing at a read-only string (e.g. a const string literal) then you will get an exception.

Paul R
+1  A: 

strtok modifies the string given to it. If you don't have the right to modify it, you might get a Segmentation Fault. strdup prevents that by copying the string.

+1  A: 

strtok modifies its first argument.

In case 1 looks like you were passing a pointer to char constant which could not be modified.

and in case 2 you were passing a modifiable copy of it returned by strdup.

codaddict
Thanks for your answer.in case 1, this char pointer isn't constant (i didn't defined it as one). so... what makes it happens?
@Shaharg: I meant, did you do something like: row->txt = "text"; If yes then you cannot modify what row->txt is pointing to, so you cannot pass row->txt to strtok.
codaddict