Copying data to a buffer that is not large enough to hold that data results in a buffer overflow. Buffer overflows are not limited to null-terminated byte strings (NTBS), but they often occur when manipulating NTBS dataoccur frequently when manipulating strings. To prevent such errors, either limit copies through truncation or, preferably, ensure that the destination is of sufficient size to hold the character data to be copied and the null-termination character. (See STR03-C. Do not inadvertently truncate a null-terminated byte string.)
Because strings are represented as arrays of characters, this rule is an instance of both ARR30-C. Do not form or use out of bounds pointers or array subscripts and ARR38-C. Guarantee that library functions do not form invalid pointers.
...
getline()
works only with buffers allocated with malloc()
. If passed a NULL
pointera null pointer, getline()
allocates a buffer of sufficient size to hold the input. As such, the user must explicitly free()
the buffer later. Do not pass NULL
to pass a null pointer to getline()
because this is a violation of MEM00-C. Allocate and free memory in the same module, at the same level of abstraction.
...
Command-line arguments are passed to main()
as pointers to null-terminated byte strings in the array members argv[0]
through argv[argc - 1]
. If the value of argc
is greater than 0, the string pointed to by argv[0]
is, by convention, the program name. If the value of argc
is greater than 1, the strings referenced by argv[1]
through argv[argc - 1]
are the program arguments.
...
Remember to add a byte to accommodate the null-terminated byte stringtermination character.
Compliant Solution (Annex K, argv
)
...
Environmental variables are loaded into process memory when the program is loaded. As a result, the length of these null-terminated byte strings can be determined by calling the strlen()
function, and the resulting length can be used to allocate adequate dynamic memory:
...
The buffer overflow can be prevented by providing a precision length to the %s
specifier. The value 123
ensures that filename
can contain the first 123 characters of name
, the .txt
extension, and the null terminator.
...
...