【问题标题】:Why is this code printing trash at the end? Why is strlen returning uncorrect values?为什么这段代码最后会打印垃圾?为什么 strlen 返回不正确的值?
【发布时间】:2019-09-11 19:46:46
【问题描述】:

我正在运行以下程序

int main(int argc, char const *argv[])
{
    char fileName[NAMESIZE];
    char buffer[BUFFSIZE];
    buffer[0] = 0;
    int bytes;

    bytes = read(0 ,fileName, NAMESIZE);
    char command[COMMANDSIZE];
    char outAux[TAGSIZE];
    fileName[bytes - 1] = 0;

    sprintf(command, "minisat %s | grep \"Number of v\" -A2 | sed 's/|//g'| sed 's/: */: /g' | sed 's/^ *//g'", fileName);

    FILE * fp;
    fp = popen(command, "r");

    while(fgets(outAux, TAGSIZE, fp)){
        strcat(buffer, outAux);
    }

    pclose(fp);
    write(1, buffer, BUFFSIZE);
    
    return 0;
}

据我了解, fgets 确实在末尾放了一个 0。但是,输出如下:

Number of variables: 3                                         
Number of clauses: 2                                         
Parse time: 0.00 s                                       
(trash)

它正确打印了我想要的内容,但随后它开始打印垃圾,好像最后没有 0

我尝试通过执行以下操作强制为 0 来解决此问题:在 while 循环的每次迭代中保存 outAux 的长度,将其添加到计数器 buffLen,然后执行 buffer[buffLen] = 0

但是,这会失败,因为 strlen 没有返回 outAux 的长度。例如,"Number of variables: 3\n" 行根据 strlen 长度为 64

如何解决我的问题? (如果可能的话,我也想知道为什么 strlen 返回不正确的值)

编辑:最初的问题来自我错误地使用 write。但是,我仍然有我原来的问题。如果我运行以下代码:

fgets(outAux, TAGSIZE, fp));
printf("%s", outAux);
printf("%d", strlen(outAux));

我得到以下输出:

Number of variables: 3
64

为什么 strlen 返回这么大的值?

【问题讨论】:

  • 因为您将 BUFFSIZE 字节发送到输出,而不是缓冲区中实际的数字。
  • 你没有使用你写的strlen
  • 不,write 会写入您告诉它写入的字节数。
  • 您将readwrite 与STDIN/STDOUT 一起使用,而不是更传统的printf/scanf,有什么特别的原因吗?后者将正确处理您的 nul 终止字符串问题。
  • 您可以将一个 3 字节的字符串存储在一个 10 字节的 buf 中。但是,如果你使用write(1, buf, 10),你将在前 3 个字节之后得到 7 个字节的垃圾。

标签: c fgets strlen


【解决方案1】:

我不知道 minisat 是什么或做什么,但我敢打赌 TAGSIZE 等于 64,并且 minisat 不会输出 fgets 识别为换行符的任何内容。因此 fgets 只是捕获管道输出,而您看到的“垃圾”只是开始时缓冲区中的剩余部分。

由于缓冲区溢出,您的代码容易出现各种未定义的行为。

【讨论】:

  • 这是可能的,但你还没有真正解释根本原因。
猜你喜欢
  • 2023-03-25
  • 1970-01-01
  • 2013-09-04
  • 1970-01-01
  • 1970-01-01
  • 2022-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多