Skip to content

* src/base/ftsystem.c: Avoid UB in ft_ansi_stream_io

Tamir Duberstein requested to merge (removed):avoid-ub into master

Per ISO/IEC 9899:

If an argument to a function has an invalid value (such as a value outside the domain of the function, or a pointer outside the address space of the program, or a null pointer, orapointer to non-modifiable storage when the corresponding parameter is not const-qualified) or a type (after promotion) not expected by a function with variable number of arguments, the behavior is undefined. If a function argument is described as being an array, the pointer actually passed to the function shall have a value such that all address computations and accesses to objects (that would be valid if the pointer did point to the first element of such an array) are in fact valid.

Per IEEE Std 1003.1:

size_t fread(void *restrict ptr, size_t size, size_t nitems, FILE *restrict stream);

The fread() function shall read into the array pointed to by ptr up to nitems elements whose size is specified by size in bytes, from the stream pointed to by stream.

Since the first argument to fread is described as being an array, its behavior is undefined when that argument is a null pointer.

Per the documentation on ft_ansi_stream_io:

If `count' is zero (this is, the function is used for seeking), a non-zero return value indicates an error.

Thus the intent is clear, and the call to fread can be skipped, avoiding UB.

Merge request reports