Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Off-by-one error
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
=== Security implications === A common off-by-one error which results in a security-related bug is caused by misuse of the [[C standard library]] <code>[[strncat]]</code> routine. A common misconception with <code>strncat</code> is that the guaranteed null termination will not write beyond the maximum length. In reality it will write a terminating null character one byte beyond the maximum length specified. The following code contains such a bug: <syntaxhighlight lang="c"> void foo (char *s) { char buf[15]; memset(buf, 0, sizeof(buf)); strncat(buf, s, sizeof(buf)); // Final parameter should be: sizeof(buf)-1 } </syntaxhighlight> Off-by-one errors are common in using the C library because it is not consistent with respect to whether one needs to subtract 1 byte β functions like <code>fgets()</code> and <code>strncpy</code> will never write past the length given them (<code>fgets()</code> subtracts 1 itself, and only retrieves {{nowrap|(length β 1)}} bytes), whereas others, like <code>strncat</code> will write past the length given them. So the programmer has to remember for which functions they need to subtract 1. On some systems ([[Endianness|little endian]] architectures in particular) this can result in the overwriting of the least significant byte of the [[frame pointer]]. This can cause an exploitable condition where an attacker can hijack the local variables for the calling routine. One approach that often helps avoid such problems is to use variants of these functions that calculate how much to write based on the total length of the buffer, rather than the maximum number of characters to write. Such functions include <code>[[strlcat]]</code> and <code>[[strlcpy]]</code>, and are often considered "safer" because they make it easier to avoid accidentally writing past the end of a buffer. (In the code example above, calling <code>strlcat(buf, s, sizeof(buf))</code> instead would remove the bug.)
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)