Why does the following C program give a bus error?

て烟熏妆下的殇ゞ 提交于 2019-12-04 05:42:27

String literals should be assigned to a const char*, as modifying them is undefined behaviour. I'm pretty sure that strtok modifies it's argument, which would explain the bad things that you see.

There are 2 problems:

  1. Make str of type char[]. GCC gives the warning foo.cpp:5: warning: deprecated conversion from string constant to ‘char*’ which indicates this is a problematic line.

  2. Your second strtok() call should have NULL as its first argument. See the docs.

The resulting working code is:

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

int main(int argc, char **argv) {
  char str[] = "one|two|three";

  char *tok = strtok(str, "|");

  while (tok != NULL) {
    printf("%s\n", tok);
    tok = strtok(NULL, "|");
  }

  return 0;
}

which outputs

one
two
three

I'm not sure what a "bus" error is, but the first argument to strtok() within the loop should be NULL if you want to continue parsing the same string.

Otherwise, you keep starting from the beginning of the same string, which has been modified, by the way, after the first call to strtok().

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!