c - 函数以某种方式从一次调用中返回两次

标签 c string gcc

我正在编写一个简单的程序来尝试实现 strtok。只是自己的一些练习

我想出了这个:

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

char * stringtok(char * str, char * delim){
    static int last;
    if(str != NULL){ last = 0; }
    char * finder;
    char * result = malloc(100);
    while(delim[0] != '\0'){
        if(finder = strchr(str+last, delim[0])){
            memcpy(result, str + last, finder - str);
            result[finder-str+1] = '\0';
            last = finder - str;
            return result;
        }
        delim++;
    }
    return NULL;
}

int main(){
    char input[100]="This is my - message - hello can - you hear me?";
    char input2[100] = "-";
    char * pch;




    pch = stringtok(input, input2);
    while(pch != NULL){
        printf("%s\n", pch);
        pch = strtok(NULL, input2);
    }
}

当我使用 gcc -ggdb ./a.out 时,我得到: “这是我的 ” 这很奇怪,所以我通过 GDB 使用断点 22 运行它,得到:

Breakpoint 1, main () at strtok.c:22
22      int main(){
(gdb) s
23          char input[100]="This is my - message - hello can - you hear me?";
(gdb)
29
(gdb)
stringtok (
    str=0x7fffffffe040 "This is my - message - hello can - you hear me?",
    delim=0x7fffffffdfd0 "-") at strtok.c:7
7           if(str != NULL){ last = 0; }
(gdb)
9           char * result = malloc(100);
(gdb)
10          while(delim[0] != '\0'){
(gdb)
11              if(finder = strchr(str+last, delim[0])){
(gdb)
12                  memcpy(result, str + last, finder - str);
(gdb)
13                  result[finder-str+1] = '\0';
(gdb)
14                  last = finder - str;
(gdb)
15                  return result;
(gdb)
19          return NULL;
(gdb)
main () at strtok.c:30
30          pch = stringtok(input, input2);
(gdb)
31          while(pch != NULL){
(gdb)
This is my
32              printf("%s\n", pch);
(gdb)
30          pch = stringtok(input, input2);
(gdb)
34          }
(gdb)
0x000000363d21ed5d in __libc_start_main () from /lib64/libc.so.6
(gdb)
Single stepping until exit from function __libc_start_main,
which has no line number information.

Program exited normally.
(gdb)

我发现很奇怪,我有一个返回结果,然后它又返回 NULL,我不太确定为什么会发生这种情况。我只是读错了gdb吗?看起来从返回结果到立即返回NULL。而且看起来我的 gdb 晚了 1 行输出,查看 printf 以及输出的实际位置

最佳答案

您的 strtok 函数无法正确处理 strNULL 的情况。第一次调用时,除了最后一个偏移量之外,您还需要保存字符串。现在,当您第二次调用它时,您在任何地方都没有任何指向原始字符串的指针。

关于c - 函数以某种方式从一次调用中返回两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28978604/

相关文章:

java - 数组索引越界

c - 为什么 Valgrind 在 calloc 语句上显示内存泄漏

mysql - 从 MySQL 的列中查找数组中的元素

string - 从多个变量创建自定义PowerShell对象

C 链表插入函数在末尾创建不需要的条目

c - 符号表与集合

c++ - 为什么library API + compiler ABI就足以保证不同版本gcc对象之间的兼容性?

c++ - 如何将 std::array 实例地址作为参数传递给 std::min_element?

c - "int *"类型的参数与 "int (*)[1000]"类型的参数不兼容

C 编程 : Error while printing all lines containing a specific word from a text file