【问题标题】:String tokenizer- strange behavior with verified array字符串标记器 - 验证数组的奇怪行为
【发布时间】:2011-04-10 14:37:32
【问题描述】:

编辑将建议纳入编码和更新问题

我必须在程序中实现一个自动换行功能,并且选择了一个贪心算法

//I use fread to take in the file in one bite, the parse the resulting array.  The 
//four lines below are from another function.
char *readBuffer= (char *) malloc(sizeof(char) * fileSize);    
int size= ftell(fp);
rewind(fp);
size_t result= fread(readBuffer, 1, size, fp);

int spaceLeft= termWidth;
int outputLines=0, tempLength, printCount-0;
char *temp, *newLine="\n";

temp= strtok(readBuffer, " "),
fputs(temp, stdout); //prints out a 11, when should be a 1, then exits

while ((outputLines < termHeight) && (temp != NULL)){
    strcat(temp, " ");
    tempLength= strlen(temp);

    if (spaceLeft > tempLength){
      fputs(temp, stdout);
      spaceLeft -= tempLength+1;
    } else {
      strcat(newLine, temp);
      spaceLeft= termWidth-(tempLength);
      outputLines++;
      newLines="\n";
    }
    temp= strtok(NULL, " ");
    printCount+= tempLength //debugger display
  }
}

通过这段代码,我验证了文件被正确读入到 readBuffer 中 fputs(readBuffer, stdout) 命令。但是,第一个 fputs 将 11 写入屏幕,而它应该是 1。然后它会跳过 while 循环并退出。

OutputLines 设置为 0,termHeight 是 termHeight=termios.ws_row-1 调用的结果。

如果 temp 正在将值打印到屏幕上,并且 (outputLines= 0) > termHeight,那么在这种情况下 temp 怎么可能为 null?

【问题讨论】:

  • 如果字符串中没有更多标记,strtok 将返回 null,也许这就是发生了什么?
  • 我是这么想的,但文件大小是 1.6KB,里面大约有 90 行文本。为什么会返回null?如果我通过fputs 输出文本而没有strtok,则会显示所有文本。
  • 文件中是否有任何 NUL 字符('\0')?这会干扰strtok()

标签: c unix malloc segmentation-fault text-processing


【解决方案1】:

部分问题可能是fgets 从文件中只检索到一行。 The man page 对此进行了描述。该代码似乎期望它读取整个文件。因此,处理第一行后 temp 将为 NULL(如果其中没有空格,则为单个标记)。

不知道您正在阅读的文本的长度,也不知道termHeighttermWidth 的值,因此不可能知道执行路径。但是在处理该行之后,段错误可能发生在对 NULL temp 值的 strlen() 调用上。虽然这不是一个完整的修复,while 语句可能应该使用&amp;&amp; 而不是||

while ((outputLines > termHeight) && (temp != NULL){

根据您希望如何处理它,您可能需要另一个fgets 调用来读取strtok 返回NULL 之后的下一行。或者,或者,使用fread 在一次调用中检索整个文件。

【讨论】:

    猜你喜欢
    • 2012-05-03
    • 1970-01-01
    • 2017-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多