is this UB? #include<stdio.h> int foobar() { FILE *fp = fopen("file.bin", "rb");…
- User
is this UB? #include<stdio.h> int foobar() { FILE *fp = fopen("file.bin", "rb"); unsigned char buffer; // note: 1 byte fread(&buffer, 1, 1, fp); return buffer; }
- Assistant
Short answer: Yes, the function can easily trigger Undefined Behavior (UB).
Longer answer: there are two different ways it can go wrong, plus a couple of minor odds-and-ends.
- Passing a null
FILE*tofread
If
fopenfails (e.g. the file does not exist, you lack permissions, …) it returnsNULL.
The C standard (C17 §7.21.8.1/1) says aboutfread:The stream shall be a valid pointer to an open file.A
NULLpointer is not “a valid pointer to an open file”, so callingfreadwith it is UB.
- Using an indeterminate value
freadreturns the number of objects actually read.
If that return value is 0 (EOF or I/O error),bufferis left unchanged → still contains an indeterminate value.
Reading (or in this case, returning) an indeterminate value of unsigned character type is UB (C17 §6.2.4/2, §6.3.2.1/2).
So even iffpis non-NULL, you still have to look atfread’s return value before you usebuffer.
- Things that are “only” bad style, not UB
• Not calling
fclose(fp)leaks a file descriptor but is not UB.
• Returning anunsigned charin anintis fine; the usual integer promotions apply and the value is preserved.
• Reading exactly one byte into a one-byte variable is perfectly OK.
A safer rewrite
#include <stdio.h> int foobar(void) { int result = EOF; // default in case of failure FILE *fp = fopen("file.bin", "rb"); if (fp) { unsigned char byte; size_t n = fread(&byte, 1, 1, fp); if (n == 1) // success result = byte; // implicit promotion to int fclose(fp); } return result; // either 0-255 or EOF (-1) }Now:
• We verify that
fopensucceeded.
• We check the return value offread.
• We close the file.
→ No undefined behavior. - Passing a null
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.