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

时间:2015-03-11 04:29:51

标签: 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以及输出实际在哪里

1 个答案:

答案 0 :(得分:0)

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