c - strerror_r 缓冲区总是空终止

标签 c posix glibc

这段代码安全吗:

strerror_r(errcode,buffer,length);
printf("Error: %s",buffer);

也就是说,如果缓冲区太小,我可以相信缓冲区是空终止的吗?从手册页:

The XSI-compliant strerror_r() is preferred for portable applications. It returns the error string in the user-supplied buffer buf of length buflen.

The GNU-specific strerror_r() returns a pointer to a string containing the error message. This may be either a pointer to a string that the function stores in buf, or a pointer to some (immutable) static string (in which case buf is unused). If the function stores a string in buf, then at most buflen bytes are stored (the string may be truncated if buflen is too small and errnum is unknown). The string always includes a terminating null byte ('\0').

我说的对吗,如果我使用符合 XSI 的版本,buffer 可能不会以 null 终止。

最佳答案

如果您使用的是 POSIX strerror_r 并且它返回非零值,我不确定您是否可以假设任何东西都在 buffer 中。您可以检查 man 3p strerror 以获得 POSIX 函数描述,但它没有说明如果 length 不够大时 buffer 会发生什么.

也许 POSIX 标准的其他部分说明了在这种情况下会发生什么,但我怀疑它没有指定。我会检查 strerror_r 的返回值,如果它不为零,则不使用 buffer,以确保安全。

在我尝试过的两个系统上,编译器将错误消息复制到缓冲区中并用 NUL 字节将其截断。在 RHEL 5.4 上,如果 strerror_r 的大小太小,它不会修改 buffer。在那种情况下,如果您在调用 sterror_r 之前没有初始化它,则 buffer 可以是任何东西。

关于c - strerror_r 缓冲区总是空终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27721278/

相关文章:

c 将多个参数传递给线程

c - 零超时的非阻塞 connect() 和 select() 返回 0

c++ - 无效的 fastbin 条目(免费)

mysql - 在 Glibc 2.11 上将 MySQL 5.1 更新到 5.6

c - 如何在方法中复制字符串?

c - 为什么在表示有符号数时 Two's complement 比 Ones' complement 更广泛地使用

c - 在 Visual C++ 中使用 char 表示固定字符串

c - 向量化模运算

c - 接收tcp数据时写入串口

c - 如何使用__malloc_hook?