分段故障strtok

时间:2014-06-16 06:57:46

标签: c segmentation-fault strtok

我试图理解为什么这段代码会给我一个分段错误! research是一个字符串,它正在打印我的令牌,但之后我有一个分段错误 你能帮帮我吗?

char buf[MAX_CHARS_PER_LINE];
strcpy(buf, research.c_str());

int n = 0;
const char * token[MAX_TOKENS_PER_LINE] = {};

for (n = 0; n < MAX_TOKENS_PER_LINE; n++)
{
    if (n == 0) token[0] = strtok(buf, DELIMITERS);
    else token[n] = strtok(0, DELIMITERS);

    if (!token[++n]) break;

    printf("%s\n", token[n]);
}

2 个答案:

答案 0 :(得分:2)

没有预先增加

if (!token[n]) break;

复制到固定长度的char数组时,始终使用strncpy - 而不是strcpy。

答案 1 :(得分:1)

很抱歉,您以非常复杂的方式处理此问题,因此似乎失去了监督。

char buf[MAX_CHARS_PER_LINE] = {0}; /* Intialise the array properly. */
strncpy(buf, research.c_str(), MAX_CHARS_PER_LINE - 1); /* Take care to not overflow the target. */

size_t n = 0; /* size_t is the proper type to index arrays. */
const char * token[MAX_TOKENS_PER_LINE] = {};

token[n] = strtok(buf, DELIMITERS);
while (token[n]  && (n < (MAX_TOKENS_PER_LINE - 1))
{
  n++;

  token[n] = strtok(0, DELIMITERS);

  printf("%s\n", token[n]);
}