While strncmp
can prevent you from overrunning a buffer, its primary purpose isn't for safety. Rather, it exists for the case where one wants to compare only the first N characters of a (properly possibly NUL-terminated) string.
From the man page:
The strcmp()
function compares the two strings s1
and s2
. It returns an integer less than, equal to, or greater than zero if s1
is found, respectively, to be less than, to match, or be greater than s2
.
The strncmp()
function is similar, except it compares the only first (at most) n
bytes of s1
and s2
.
Note that strncmp
in this case cannot be replaced with a simple memcmp
, because you still need to take advantage of its stop-on-NUL behavior, in case one of the strings is shorter than n
.
If strcmp
causes a buffer overrun, then one of two things is true:
- Your data isn't expected to be NUL-terminated, and you should be using
memcmp
instead.
- Your data is expected to be NUL-terminated, but you've already screwed up when you populated the buffer, by somehow not NUL-terminating it.
Note that reading past the end of a buffer is still considered a buffer overrun. While it may seem harmless, it can be just as dangerous as writing past the end.
Reading, writing, executing... it doesn't matter. Any memory reference to an unintended address is undefined behavior. In the most apparent scenario, you attempt to access a page that isn't mapped into your process's address space, causing a page fault, and subsequent SIGSEGV. In the worst case, you sometimes run into a byte, but other times you run into some other buffer, causing inconstant program behavior.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…