【问题标题】:C Programming: strtok delivers segmentation faultC 编程:strtok 提供分段错误
【发布时间】:2019-12-03 06:18:30
【问题描述】:

我正在尝试通过空格和制表符对字符串进行标记。但是,当我运行我的程序时,我在尝试打印令牌时收到分段错误错误。我不明白为什么会发生这种情况,因为无论我使用token 还是使用*token 尊重令牌,打印语句都不起作用。以下是我的代码:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char string = "String1 String2 String3";
    char *token = strtok(string," \t"); /* The atomic weights and names are separated by either a space or tab */

    while (token != NULL) /* While there is still content for us to read */
    {
        printf("token = %s\n", *token);
        token = strtok(NULL, " \t"); 
    }

    exit(1);
}

【问题讨论】:

  • char string = 应该是 char string[] =
  • 打开编译器警告——如果你允许编译器会指出一些非常明显的问题。
  • 您将string 声明为char 而不是char[]。由于有点神秘的原因,这不是错误,但至少应该发出警告。
  • 始终检查编译器的警告!对于gcc,我使用gcc -Wall -Wextra -pedantic
  • 另外,您为什么决定在打印时取消引用token

标签: c string token


【解决方案1】:

首先,char string 必须是 char *stringchar string[]。您正在尝试将整个字符串分配给单个 char

其次,字符串文字是只读数据,但strtok() 修改了给定的char 缓冲区。因此,您的代码具有未定义的行为,因为它正在尝试修改只读内存。

如果将char string 更改为char string[],则字符串文字数据将在运行时复制到可写缓冲区中。然后在调用printf() 时将*token 更改为token,因为%s 需要一个char* 指针,而不是单个char。然后您的代码将按预期工作:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char string[] = "String1 String2 String3";
    char *token = strtok(string," \t"); /* The atomic weights and names are separated by either a space or tab */

    while (token != NULL) /* While there is still content for us to read */
    {
        printf("token = %s\n", token);
        token = strtok(NULL, " \t");
    }

    //exit(1);
    return 1;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2023-03-24
    相关资源
    最近更新 更多