Skip to content
TheChatArchiveThe Chat Archive
o3-2025-04-16· OpenAIHugging Face LMArena Human Preference 140K

is this UB? #include<stdio.h> int foobar() { FILE *fp = fopen("file.bin", "rb");…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with chatgpt-4o-latest-20250326’s answer.
  1. 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; }

  2. 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.


    1. Passing a null FILE* to fread

    If fopen fails (e.g. the file does not exist, you lack permissions, …) it returns NULL.
    The C standard (C17 §7.21.8.1/1) says about fread:

    The stream shall be a valid pointer to an open file.
    

    A NULL pointer is not “a valid pointer to an open file”, so calling fread with it is UB.


    1. Using an indeterminate value

    fread returns the number of objects actually read.
    If that return value is 0 (EOF or I/O error), buffer is 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 if fp is non-NULL, you still have to look at fread’s return value before you use buffer.


    1. Things that are “only” bad style, not UB

    • Not calling fclose(fp) leaks a file descriptor but is not UB.
    • Returning an unsigned char in an int is 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 fopen succeeded.
    • We check the return value of fread.
    • We close the file.
    → No undefined behavior.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.