Chinaunix首页 | 论坛 | 博客
  • 博客访问: 27479
  • 博文数量: 16
  • 博客积分: 672
  • 博客等级: 上士
  • 技术积分: 150
  • 用 户 组: 普通用户
  • 注册时间: 2010-06-02 22:48
文章分类

全部博文(16)

文章存档

2011年(2)

2010年(14)

我的朋友

分类: C/C++

2010-10-13 11:55:19

code:

31 char *buf1 = "aaa,bbb";
 32 char* token = strtok( buf1, ",");
 33 while( token != NULL )
 34 {
 35 printf( "%s ", token );
 36 token = strtok( NULL, ",-|");
 37 }


编译正常
运行错误:Segmentation fault
调试:
    在line32 char* token = strtok( buf1, ",");
Program received signal SIGSEGV, Segmentation fault.
0x00551df7 in strtok () from /lib/libc.so.6

原因分析:
man strtok

发现:BUGS
       Avoid using these functions.  If you do use them, note that:

              These functions modify their first argument.

              These functions cannot be used on constant strings.

              The identity of the delimiting character is lost.

              The  strtok()  function  uses a static buffer while parsing, so it's not thread safe. Use strtok_r() if this matters to you.


因为 buf1 是一个常量,所以出错了;

代码修改:

31 char buf1[] = "aaa,bbb";
 32 char* token = strtok( buf1, ",");
 33 while( token != NULL )
 34 {



正确了!!!
阅读(1270) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~