C执行垃圾邮件时功能/对象未返回一致的输出

时间:2019-05-10 09:19:41

标签: c printf stdout

我正在研究一个微型项目,该项目将其数据库存储在本地文件中并对其进行操作。我仍然是编程的新手,所以这种输出随机性超出了我的调试专业知识。到目前为止的代码很大,所以我只粘贴相关的内容。

extern void returnRecord(FILE *fp, fpos_t pos, char *retArr)
{ 
  char tok = delim;  //for strtok (delimiter = control char 21)
  char tmpArr[612]; //for strtok
  char *segment;     //pointer to save strtok return
  fsetpos(fp, &pos);  //beginning of the record
  fgets(tmpArr, 611, fp); 
  strtok(tmpArr,&tok);
  strcpy(retArr, tmpArr);
  strcat(retArr, "\n");
  segment = strtok(NULL, &tok); //tmpArr now has the author name

  int tmpCount = 0;
  char c = segment[0];
  int counter = strlen(retArr);
  while((c != 6) && (c != 0))
    {
      retArr[counter++] = c;
      c = segment[++tmpCount];
    }
  retArr[counter++] = '\n';



  segment = strtok(NULL, &tok); //tmpArr now has the rack number

  tmpCount = 0;
  c = segment[tmpCount++];
  while((c != 6) && (c != 0))
    {
      retArr[counter++] = c;
      c = segment[tmpCount++];
    }

  retArr[counter++] = '\n';


  segment = strtok(NULL, &tok); //tmpArr now has the book title

  tmpCount = 0;
  c = segment[tmpCount++];
  while((c != 6) && (c != 0) && (c != '\n'))
    {
      retArr[counter++] = c;
      c = segment[tmpCount++];
    }

  retArr[counter] = '\0';
  return;
}

以下不是C,而是数据库中示例记录的描述:

<...> everything inside is my explanation
<6s> means a bunch of buffer characters that are all 0x06

3<delim>Isaac Newton<6s><delim>3<6s><delim>Philosophiæ Naturalis Principia Mathematica<6s><new line only if it's not the final record>

(delim is: #define delim 21 //at the top)

可能有一些冗余,但是优化不是我的直接关注,因为输出(char * retArr)并不总是一致的。这是我向可执行文件发送垃圾邮件时的一些输出。

printf("%s\n strlen: %d\n", ret2, strlen(ret2)); //print code
(the first execution here shows the full correct output)
sflash@debian:~/Documents/AOHI/experimental/books$ ./exe
6
Stress test | boooiafnakekjfn/;
4124
e0q-pjrnoibq3uitu0o;@lt@qjtoilqnkubneugbq3tq3
 strlen: 84
sflash@debian:~/Documents/AOHI/experimental/books$ ./exe
6
Stress test | boooiafnakekjfn/;
41245
e0q-pjrn
 strlen: 48
sflash@debian:~/Documents/AOHI/experimental/books$ ./exe
6
Stress test | boooiafnakekjfn/;
41
45
 strlen: 39

当我快速运行该程序时,代码似乎在跳一些迭代。修复此问题非常重要,因为我打算在循环内调用此函数/对象。

1 个答案:

答案 0 :(得分:0)

问题已由一些程序员大兄指出,我一直在使用strtok()错误且数组大小不匹配。分隔符必须以NULL字符结尾。