c - 每次调用 strtok_r() 时都会出现段错误,即使在简单的情况下也是如此
问题描述
我已经阅读了strtok_r的手册,并且我相对确定我使用它是正确的,但它每次都会出现段错误。
所以我决定写一个快速测试程序,发现这也有段错误:
//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)
我只在标准输入中放了“测试”,所以我知道它没有溢出。我在这里做错了吗?这是我能想到的最简单的使用场景,但它仍然会中断。
解决方案
试试这个方法:
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);
}
推荐阅读
- java - Stream.of 和 IntStream.range 有什么区别?
- pycharm - PyCharm如何设置默认重构重命名范围
- python - 将文件的内容从下到上翻转,第一行除外
- python-3.x - 在创建本地文件的动态路径以在我用 Django 开发的 Web 应用程序中工作时需要帮助
- python - 安装 docker 失败“如果安装 docker,请清理以前的 docker-py 包”,语法错误
- google-apps-script - 如果已在 Google 表格中预订,请避免在两个日期之间预订房间
- ios - iphone12录视频丢帧,视口图像稳定
- javascript - jquery jstepper在保持最小值时没有调用文本框更改事件
- c# - C# 无限循环。如何应用循环控制变量?
- c - 为什么 Sleep() 函数会阻止整个循环工作?