While strncmp can prevent you from intercepting a buffer, its main purpose is not safe. Rather, it exists for the case when you need to compare only the first N characters of the string ( correctly , possibly with zero termination).
On the page :
The strcmp() function compares two strings s1 and s2 . It returns an integer less than, equal to or greater than zero, if s1 found, respectively, less to match or be greater than s2 .
The strncmp() function is similar, except that it only compares the first (at most) n bytes s1 and s2 .
Note that strncmp cannot be replaced with simple strncmp in this case, because you still need to use its stop-on-NUL behavior if one of the lines is shorter than n .
If strcmp causes a buffer overflow, then one of two things is true:
- Your data should not be NUL-terminated, and you should use
memcmp . - It is expected that your data will be completed using the NUL, but you already messed up when you filled the buffer, somehow not completing its NUL.
Note that reading beyond the end of the buffer is still considered buffer overflow. . Although this may seem harmless, it can be as dangerous as writing at the end.
Reading, writing, fulfilling ... it doesn't matter. Any memory link to an unintended address is undefined. In the most obvious scenario, you are trying to access a page that does not appear in the address space of your process, which results in a page error and subsequent SIGSEGV. In the worst case, you sometimes run byte \ 0, but in other cases, you run some other buffer, causing inconsistent program behavior.
source share