gpt4 book ai didi

c - 每次调用 strtok_r() 时都会出现段错误,即使在简单的情况下也是如此

转载 作者:行者123 更新时间:2023-11-30 14:42:03 24 4
gpt4 key购买 nike

我已阅读manual对于 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)

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

最佳答案

试试这个方法:

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);
}

关于c - 每次调用 strtok_r() 时都会出现段错误,即使在简单的情况下也是如此,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54612374/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com