autoconf: Buffer Overruns

1 
1 13.5 Buffer Overruns and Subscript Errors
1 =========================================
1 
1 Buffer overruns and subscript errors are the most common dangerous
1 errors in C programs.  They result in undefined behavior because storing
1 outside an array typically modifies storage that is used by some other
1 object, and most modern systems lack runtime checks to catch these
1 errors.  Programs should not rely on buffer overruns being caught.
1 
1    There is one exception to the usual rule that a portable program
1 cannot address outside an array.  In C, it is valid to compute the
1 address just past an object, e.g., `&a[N]' where `a' has `N' elements,
1 so long as you do not dereference the resulting pointer.  But it is not
1 valid to compute the address just before an object, e.g., `&a[-1]'; nor
1 is it valid to compute two past the end, e.g., `&a[N+1]'.  On most
1 platforms `&a[-1] < &a[0] && &a[N] < &a[N+1]', but this is not reliable
1 in general, and it is usually easy enough to avoid the potential
1 portability problem, e.g., by allocating an extra unused array element
1 at the start or end.
1 
1    Valgrind (http://valgrind.org/) can catch many overruns.  GCC users
1 might also consider using the `-fmudflap' option to catch overruns.
1 
1    Buffer overruns are usually caused by off-by-one errors, but there
1 are more subtle ways to get them.
1 
1    Using `int' values to index into an array or compute array sizes
1 causes problems on typical 64-bit hosts where an array index might be
1 2^31 or larger.  Index values of type `size_t' avoid this problem, but
1 cannot be negative.  Index values of type `ptrdiff_t' are signed, and
1 are wide enough in practice.
1 
1    If you add or multiply two numbers to calculate an array size, e.g.,
1 `malloc (x * sizeof y + z)', havoc ensues if the addition or
1 multiplication overflows.
1 
1    Many implementations of the `alloca' function silently misbehave and
1 can generate buffer overflows if given sizes that are too large.  The
1 size limits are implementation dependent, but are at least 4000 bytes
1 on all platforms that we know about.
1 
1    The standard functions `asctime', `asctime_r', `ctime', `ctime_r',
1 and `gets' are prone to buffer overflows, and portable code should not
1 use them unless the inputs are known to be within certain limits.  The
1 time-related functions can overflow their buffers if given timestamps
1 out of range (e.g., a year less than -999 or greater than 9999).
1 Time-related buffer overflows cannot happen with recent-enough versions
1 of the GNU C library, but are possible with other implementations.  The
1 `gets' function is the worst, since it almost invariably overflows its
1 buffer when presented with an input line larger than the buffer.
1