【问题标题】:Empty string input with read system call causes Segmentation Fault带有读取系统调用的空字符串输入导致分段错误
【发布时间】:2019-01-24 12:12:14
【问题描述】:

我正在尝试使用 read(int fd, void *buf, size_t count); 从 STDIN 读取输入 当输入为 EOF 时,我应该如何处理?还是空字符串?目前,我遇到了分段错误

这里是sn-p的代码:

int rd;
char buf[100];
rd = read(0, buf, 99);
buf[strcspn(buffer, "\n")] = 0;

谢谢

【问题讨论】:

  • 您的代码假定字符串包含可能不正确的\n 位。查看read 的手册页。它告诉你它读取了多少字节。

标签: c operating-system segmentation-fault system


【解决方案1】:

与所有其他字符串函数一样,strcspn 依赖于以空结尾的字符串开头。

如果输入不包含换行符,则strcspn 函数将由于缺少终止符而超出范围。

您还需要处理read返回文件结束或错误的情况,这由它返回0-1(分别)表示。正如指定的in the manual(你真的应该阅读!)。

只需在 read 调用之后的适当位置直接添加终止符,但前提是 read 成功:

rd = read(STDIN_FILENO, buf, sizeof buf - 1);  // sizeof buf relies on buf being an actual array and not a pointer
if (rd == -1)
{
    // Error, handle it
}
else if (rd == 0)
{
    // End of file, handle it
}
else
{
    // Read something

    buf[rd] = '\0';  // Terminate string

    // Terminate a newline
    buf[strcspn(buf, "\n")] = '\0';  // Truncate at newline (if any)
}

【讨论】:

  • 谢谢!这有帮助:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多