The code you provided is not invoking undefined behavior (UB) in itself, but it may lead to other issues depending on the context or usage. Let's break it down clearly.
🧩 Code:
#include <stdio.h>
int foobar() {
FILE *fp = fopen("file.bin", "rb");
unsigned char buffer; // note: 1 byte
fread(&buffer, 1, 1, fp);
return buffer;
}
✅ What's fine:
- File open mode (
"rb"): Correct mode for reading a binary file.
- Declared buffer (
unsigned char buffer): Correct type for reading a single byte.
- Use of
fread: You read one byte (size=1, count=1) into a buffer of size one — that's okay.
⚠️ Potential Problems:
1. No NULL-check for fp
FILE *fp = fopen("file.bin", "rb");
If the file does not exist or can't be opened, fopen returns NULL. Using fp in that case causes undefined behavior when you call fread.
👉 Fix: Always check if fp != NULL.
if (!fp) {
// handle error
}
2. Unspecified return value if fread fails
If fread doesn't read one byte (e.g., end of file, error), then your buffer variable contains an indeterminate value, and returning it as int may propagate garbage, but not UB by itself.
According to the C standard:
If an object is read from an input stream when no characters are available (e.g., due to EOF), the contents of the object become indeterminate. Using indeterminate values might be UB depending on exact usage (like using it in pointer arithmetic etc), but just returning it as int is most likely implementation-defined or harmless (though still bad design without checking).
👉 Better version:
int foobar() {
FILE *fp = fopen("file.bin", "rb");
if (!fp) {
// Handle file open error
return -1; // or other sentinel
}
unsigned char buffer = 0;
size_t n = fread(&buffer, 1, 1, fp);
fclose(fp);
if (n != 1) {
// Read error or EOF
return -1; // or other sentinel to indicate failure
}
return buffer; // safe usage
}
3. fclose(fp) is missing
Leaving the file open may not cause UB immediately, but it's a resource leak and shouldn't be ignored.
✅ In Short:
| Part | UB? | Notes |
|---|
Reading 1 byte into unsigned char | ❌ | Fine |
Using result without checking fread return | ⚠️ | May use indeterminate value |
Not checking fp != NULL | ✅ | May cause UB |
| Not closing the file | ❌ | Resource leak but not UB |
✅ Recommendation:
Avoid subtle bugs: always check fopen and fread return values, and close files.
Let me know if you want help adapting this to read more bytes or work with error handling!