【发布时间】:2019-06-19 14:47:47
【问题描述】:
我正在尝试对从文件中提取的字符串进行标记。 strtok_r 在第一个子字符串上正常工作,然后返回 null(以及分段错误,因为我尝试将 strndup 转换为另一个 var)
char buffer[500];
char * c;
char * c1;
char * c2;
//....
while(fgets(buffer, sizeof(buffer), f) != NULL){
c2 = buffer;
printf("%s\n", buffer);
c = strtok(c2, ":");
for(int i = 0; i < 4; i++){
c = strtok(NULL, ":");
printf("%s\n", c);
}
if(strcmp(c, argp->origen) == 0){
c = strtok(NULL, ":");
printf("%s\n", c);
if(strcmp(c, argp->destino) == 0){
nodo = malloc(sizeof(lista_vuelo));
c2 = buffer;
c = strtok_r(c2, ":", &c1);
nodo->IdReg = atoi(c);
printf("\n%d test\n", nodo->IdReg); //Works until here
c = strtok_r(NULL, ":", &c1);
printf("\n%s\n", c); //Prints null and then segmentation fault
nodo->Idvuelo = strndup(c, strlen(c));
printf("\n%s\n", nodo->Idvuelo);
//....
文件输入:
3:IBE3674:02-04-2019:19-45:马德里:柏林:巴拉哈斯:泰格尔:伊比利亚:210:35:6:T4:60:N
输出:
3 次测试 -> 预期输出
(null)
Violación de segmento (`core' generado) -> Segmentation fault, (null) should be IBE3674
【问题讨论】:
-
你的意见是什么?
-
@Yastanub 从文件中读取,输入为 3:IBE3674:02-04-2019:19-45:Madrid:Berlin:Barajas:Tegel:IBERIA:210:35:6:T4 :60:N // 将其添加到主帖
-
你期望 strtok 返回什么?为什么?
-
指向下一个标记的指针,以便我可以将其添加到结构中包含的字符指针中
-
好吧,如果
strtok返回NULL之后你的程序崩溃了,你应该考虑在使用NULL指针之前检查返回值。如果您已经将NULL传递给printf,则会调用未定义的行为。之后您仍然忽略NULL并将指针输入strlen和strndup。如果您将NULL输入到大量意想不到的函数中,那么崩溃也就不足为奇了