【问题标题】:strtok_r() segfaults every time I call it, even in simple situations每次调用 strtok_r() 时都会出现段错误,即使在简单的情况下也是如此
【发布时间】:2019-02-10 00:57:17
【问题描述】:

我已经阅读了 strtok_r 的 manual 并且我比较确定我使用它是正确的,但它每次都会出现段错误。

所以我决定写一个快速测试程序,发现这也是段错误:

//This define probably not necessary
//POSIX_C_SOURCE is defined as 200809L on my system
//It still doesn't work even with this define though..
#define _POSIX_SOURCE 

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

int main(void)
{
    char input[255];
    char* token;
    char** saveptr;

    memset(input, 0, sizeof(char) * 255);
    fgets(input, sizeof(input), stdin);
    token = strtok_r(input, ":", saveptr);
}

来自 valgrind 的回溯:

==15796== Command: ./a.out
==15796== 
==15796== Use of uninitialised value of size 8
==15796==    at 0x4EDABA4: strtok_r (strtok_r.c:73)
==15796==    by 0x10878B: main (in /home/pluh/a.out)
==15796== 
==15796== Invalid write of size 8
==15796==    at 0x4EDABA4: strtok_r (strtok_r.c:73)
==15796==    by 0x10878B: main (in /home/pluh/a.out)
==15796==  Address 0x0 is not stack'd, malloc'd or (recently) free'd
==15796== 
==15796== 
==15796== Process terminating with default action of signal 11 (SIGSEGV)

我只在标准输入中加入了“test”,所以我知道它没有溢出。我在这里做错了吗?这是我能想到的最简单的使用场景,但它仍然会中断。

【问题讨论】:

  • saveptr 未初始化。您应该传递一个指向char* 的指针,让strtop_r 返回saveptr 的值,而不是未初始化的char ** 指针。

标签: c strtok


【解决方案1】:

试试这个方法:

int main(void)
{
    char input[255];
    char* token;
    char* saveptr;

    fgets(input, sizeof(input), stdin);
    token = strtok_r(input, ":", &saveptr);

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

【讨论】:

  • 感谢您的澄清,我应该意识到 strtok_r 会修改指针,因此我必须通过引用而不是值传递它。这是漫长的一天..
  • 可能通过参数返回地址的函数需要我在这里指出的行为。如果一个函数要检索int,例如i,通过你必须传递给函数&i的参数,显然如果函数要检索e指针,你应该声明一个指针(例如char *p)并传递给函数 &p。
猜你喜欢
  • 1970-01-01
  • 2011-01-14
  • 2014-05-29
  • 2021-01-01
  • 2020-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多