7

As I was writing a unit test, I stumbled upon some odd behavior from glibc, regarding "%p" and the NULL pointer.

If I have a line such as printf("NULL pointer is %p\n", NULL);, then I see NULL pointer is (nil) printed to the screen, as I expected.

If I instead use the wide-character version: wprintf(L"NULL pointer is %p\n", NULL);, then it prints out NULL pointer is (, and stops at the opening parenthesis. If I print a non-NULL pointer, it prints that pointer, both normal and wide-character versions. Is this a known bug of glibc, or am I just missing something?

NB: I realize that the C standard says that pointers with %p are converted in an implementation-defined manner; it just seems unusual to just print ( for a NULL pointer.

4

2 回答 2

8

这绝对是一个错误:https ://sourceware.org/git/gitweb.cgi?p=glibc.git;a=blob;f=stdio-common/vfprintf.c;hb=c15cf13a8a672bd27bf3d94b995c52872eed537d#l932

 934             /* Write "(nil)" for a nil pointer.  */                           \
 935             string = (CHAR_T *) L_("(nil)");                                  \
 936             /* Make sure the full string "(nil)" is printed.  */              \
 937             if (prec < 5)                                                     \
 938               prec = 5;                                                       \
 939             is_long = 0;        /* This is no wide-char string.  */           \
 940             goto LABEL (print_string);                                        \

L_("(nil)")扩展为 wprintf ,L"(nil)"但几行之后is_long设置为0(即 false)。结果string被解释为窄字符串,因此打印它将在其第一个零字节处停止,即在(.

报告的错误链接:https ://sourceware.org/bugzilla/show_bug.cgi?id=16890 - 这在 glibc 的 2.20 版中已修复。

有趣的是,这个错误似乎已经存在了将近 15 年,然后才被发现并修复 - 在报告后的 2 天内!

于 2014-07-28T19:07:24.660 回答
1

在 Ubuntu 14.04 LTS 上确认;GNU C 库(Ubuntu EGLIBC 2.19-0ubuntu6)。

至少在 Debian glibc 中,这似乎是一个已报告的错误;该错误已于2014 年 5 月 1 日修复,应该在 Glibc 2.20 中可用。等待上游更新。

于 2014-07-28T19:05:59.827 回答