On Fri, 07 May 2004 01:48:29 +0200, Morten Nilsen <[EMAIL PROTECTED]>  said:

>   **foo = "Spin the big yellow thing";

> results Spin the big yellow thing
> Segmentation fault
> 
> If anyone can give me a tip about why this segfaults when using strtok,
> I'd be very happy :)

Subtle bug. ;)

First, we point **foo at a copy of the string.  Then we call strtok() on that
string.  Two things to note:

1) strtok *modified* the string to keep track of its state between calls (so it
knows where to pick up parsing on the next call).

2) gcc by default will put string constants in a non-writable memory segment
so they can't be accidentally splatted.

Solutions:

1)  **foo = strdup("Spin the big yellow thing");   

This will malloc() some space, copy the string into it.  Remember that for good
programming practice, you will need to free() that string if/when you're done with
it.

2) If using gcc, compile with -fwriteable-strings.  This doesn't fix your real
problem, but at least you won't crash.

Attachment: pgp00000.pgp
Description: PGP signature

Reply via email to