Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

C, strtok

Name: Anonymous 2010-02-16 13:01

Hello /prog/

Could anyone help me with using the C function strtok and strtok_r?

I've read the man pages and it doesn't provide much help. Try compiling this code example gotten from the man pages:

http://pastebin.com/d11d44ccf

Name: Anonymous 2010-02-17 1:24

>>1
So, since no one else has posted the answer yet, it's because string literals cannot be modified, and strtok modifies its string argument (it replaces the tokens with null bytes). If you attempt to modify a string literal, poof, segfault.

Wrap it up in a strdup(), like this:

char *buf = strdup("5/90/45");

That gives you a mutable copy. Then free() it when you're done. Adding strdup() to both calls fixes it.

Also, building with g++ or gcc in C99 mode would give you warning: deprecated conversion from string constant to ‘char*’. String literals are const, and strtok takes non-const.

And for everyone who complains about strtok(), it's only unsafe in a multi-threaded environment, and only on some platforms. AFAIK most platforms actually store strtok()'s internal state in a thread-local.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List