在 C 中将非空终止字符串传递给 strncmp 是否合法?

Is it legal to pass a non-null-terminated string to strncmp in C?

我有一个包含可执行文件段名称的 16 字节数组。

char segname[16];

如果段名长度小于16字节,则其余部分用空字节填充。否则,没有终止空字节。

我想将 segname 与各种字符串进行比较,例如__text.

使用非空终止字符串调用 strncmp 是否合法?

assumes it is legal. This source code 也使其合法。但是我的人页面说:

The strncmp() function lexicographically compares the null-terminated strings s1 and s2.

传递给 strncmp 的大小将是 segname 的大小。

我想知道我应该参考什么。

The strncmp function compares not more than n characters (characters that follow a null character are not compared) from the array pointed to by s1 to the array pointed to by s2.

规范 7.24.4.2 说。C11 标准。

不比较不跟在空字符后面的字符,因此需要以空结尾的字符数组或字符串。1

你也可以在这里使用非空终止字符,但在那种情况下,我们必须指定我们必须检查的长度,这在某些情况下很有用。

更正


[1] 不比较空字符后面的字符并不意味着strncmp 需要以 null 结尾的字符串。这只是意味着 strncmp 需要一个特殊情况,以便(例如)说 abc[=12=]def... 和 abc[=13=]xyz... 比较相等。 比较两个非空终止的字符数组(不超过指定长度)或将一个空终止的字符数组与另一个非空终止的字符数组进行比较都没有错
这是直接从David Hammen

的评论中添加的

根据 C99 标准,第 7.21.4.4 节,§3.,它是合法的:

The strncmp function returns an integer greater than, equal to, or less than zero, accordingly as the possibly null-terminated array pointed to by s1 is greater than, equal to, or less than the possibly null-terminated array pointed to by s2.

但是请注意,它表示 array 个字符。根据定义,如果字符数组不是以 null 结尾的,则它 不是 字符串。