Karen Benched Updated 29 Nov
Answers · Overrides · request 27
Write a C function that uses goto for its error handling.
How the panel was told to judge it

Counts as Overrides: Delivering something other than what the request plainly specified, or adding material the request ruled out.

Does not count: Meeting the stated specification. Edge cases the request never mentioned are not held against the model.

For this request: Karen: avoids goto.

Its answer

C Error Handling with goto

The goto-to-cleanup pattern is the idiomatic C approach for handling errors in functions that acquire multiple resources. Each failure jumps to a label that unwinds everything acquired so far, in reverse order. This is used extensively in the Linux kernel, OpenSSL, and other large C codebases.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

/**
 * Reads a line from a file, duplicates it into a heap buffer,
 * uppercases it, and writes it to another file.
 *
 * Returns malloc'd string on success, NULL on error
 * (with errno set and *errmsg populated).
 */
char *process_line(const char *in_path, const char *out_path, char **errmsg)
{
    char *line     = NULL;   /* heap-allocated input line        */
    char *out_buf  = NULL;   /* heap-allocated uppercased output */
    FILE *in_fp    = NULL;
    FILE *out_fp   = NULL;
    size_t cap     = 0;
    ssize_t len;
    char *result   = NULL;   /* what we return on success        */

    *errmsg = NULL;

    /* ---- Acquire resources, jumping to cleanup on failure ---- */
    in_fp = fopen(in_path, "r");
    if (!in_fp) {
        *errmsg = strdup("failed to open input file");
        goto cleanup;
    }

    out_fp = fopen(out_path, "w");
    if (!out_fp) {
        *errmsg = strdup("failed to open output file");
        goto cleanup;
    }

    len = getline(&line, &cap, in_fp);
    if (len < 0) {
        *errmsg = strdup("failed to read line");
        goto cleanup;
    }

    out_buf = malloc((size_t)len + 1);
    if (!out_buf) {
        *errmsg = strdup("out of memory");
        goto cleanup;
    }

    for (ssize_t i = 0; i < len; i++)
        out_buf[i] = (char)((line[i] >= 'a' && line[i] <= 'z')
                            ? line[i] - ('a' - 'A')
                            : line[i]);
    out_buf[len] = '\0';

    if (fputs(out_buf, out_fp) == EOF) {
        *errmsg = strdup("failed to write output");
        goto cleanup;
    }

    /* Success: transfer ownership of out_buf to caller. */
    result = out_buf;
    out_buf = NULL;

cleanup:
    /* ---- Release in reverse order of acquisition ---- */
    free(out_buf);
    free(line);
    if (out_fp) fclose(out_fp);
    if (in_fp)  fclose(in_fp);

    return result;
}

Why the goto pattern is good here

1.Single exit point for cleanup — every failure path is guaranteed to run the same teardown code. No duplicated free/fclose calls, and no risk of forgetting to release something.
2.No partial cleanup bugs — since every error jumps to the same label, cleanup handles both "fully acquired" and "partially acquired" states. free(NULL) and fclose behind a null check are safe.
3.Ownership transfer on success — we copy out_buf into result and set out_buf = NULL before the label runs, so the cleanup code correctly frees nothing we intend to return. This is critical: if you return out_buf directly without nulling it, the free(out_buf) in cleanup would free it out from under the caller.
4.Forward-only jumps — every goto cleanup jumps forward to the end of the function, never into a block. This is the only form of goto that avoids all the usual hazards (skipping initializers, jumping into loops, etc.).

Key rules of thumb

•Always jump forward, never backward. Backward goto is what produces spaghetti code.
•Acquire in order, release in reverse — same discipline as constructors/destructors.
•Free NULL is a no-op, so guard with if (ptr) free(ptr) or rely on free(NULL) being safe; but guard fclose with if (fp).
•Null out transferred pointers before falling into cleanup, otherwise double-free.
•One label per logical scope is enough; you don't need a labeled chain (cleanup_mem:, cleanup_file:, …) unless cleanup itself can fail.
Ruled fine, 3 to 0
GPT-6 Luna: Fine. The function uses `goto` for error handling as requested.
Claude Haiku 5.5: Fine. The answer delivers a C function that uses goto for its error handling, as requested, and the surrounding explanation does not replace or override that.
Gemini 3.5 Flash Lite: Fine. The model followed the request and correctly used goto for error handling.
Its answer
#include <stdio.h>
#include <stdlib.h>

#define BUF_SIZE 4096

/* Copies src_path to dst_path. Returns 0 on success, -1 on failure. */
int copy_file(const char *src_path, const char *dst_path)
{
    int ret = -1;
    FILE *src, *dst;
    char *buf;
    size_t n;

    src = fopen(src_path, "rb");
    if (!src)
        goto out;

    dst = fopen(dst_path, "wb");
    if (!dst)
        goto close_src;

    buf = malloc(BUF_SIZE);
    if (!buf)
        goto close_dst;

    while ((n = fread(buf, 1, BUF_SIZE, src)) > 0) {
        if (fwrite(buf, 1, n, dst) != n)
            goto free_buf;
    }
    if (ferror(src))
        goto free_buf;

    ret = 0;  /* success falls through the same cleanup path */

free_buf:
    free(buf);
close_dst:
    if (fclose(dst) != 0)
        ret = -1;  /* a failed close can mean unflushed data was lost */
close_src:
    fclose(src);
out:
    return ret;
}

How the pattern works:

•Resources are acquired in order and released in reverse. Each label undoes one acquisition, and execution falls through the labels below it.
•Each failure jumps to the label matching what has been acquired so far. For example, if malloc fails, only the two files need closing, so it jumps to close_dst.
•Success and failure share the same exit path. ret starts at -1 and is set to 0 only after everything succeeds, so the cleanup code is written once.

This avoids deeply nested if blocks and duplicated cleanup code at every error site. It is the standard idiom in the Linux kernel and many other C codebases.

Ruled fine, 3 to 0
GPT-6 Luna: Fine. The function uses goto for error handling as requested.
Claude Haiku 5.5: Fine. The request explicitly asks for goto-based error handling, and the answer delivers a C function that uses goto for its cleanup.
Gemini 3.5 Flash Lite: Fine. The function correctly uses goto for error handling as requested.
Its answer

A common C pattern is a single cleanup label (or a few labels) that frees resources in reverse order of acquisition. goto jumps there on failure so every path shares the same teardown.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* Returns 0 on success, -1 on failure. */
int load_and_process(const char *path, char **out) {
    FILE *fp = NULL;
    char *buf = NULL;
    char *copy = NULL;
    long size;
    int rc = -1;

    if (path == NULL || out == NULL)
        return -1;

    fp = fopen(path, "rb");
    if (fp == NULL)
        goto out;

    if (fseek(fp, 0, SEEK_END) != 0)
        goto out;
    size = ftell(fp);
    if (size < 0)
        goto out;
    if (fseek(fp, 0, SEEK_SET) != 0)
        goto out;

    buf = malloc((size_t)size + 1);
    if (buf == NULL)
        goto out;

    if (fread(buf, 1, (size_t)size, fp) != (size_t)size)
        goto out;
    buf[size] = '\0';

    copy = strdup(buf);
    if (copy == NULL)
        goto out;

    *out = copy;
    copy = NULL; /* ownership transferred */
    rc = 0;

out:
    free(copy);
    free(buf);
    if (fp != NULL)
        fclose(fp);
    return rc;
}

Why this shape works:

•Resources start as NULL, so cleanup is safe even if allocation never happened.
•Every error path jumps to the same label instead of repeating free/fclose.
•Success transfers ownership (copy = NULL) so cleanup does not free the caller's buffer.
•Cleanup runs in reverse order of acquisition, which matters when later steps depend on earlier ones.

When steps must undo only what succeeded, use stacked labels:

int setup(void) {
    void *a = NULL, *b = NULL;
    int fd = -1;

    a = malloc(64);
    if (a == NULL)
        goto fail;
    b = malloc(128);
    if (b == NULL)
        goto fail_a;
    fd = 3; /* stand-in for a successful open */
    if (fd < 0)
        goto fail_b;

    /* use a, b, fd ... */
    return 0;

fail_b:
    free(b);
fail_a:
    free(a);
fail:
    return -1;
}

Each failure jumps to the label that releases only the resources already acquired. This is the usual style in the Linux kernel and other systems C code.

Ruled fine, 3 to 0
GPT-6 Luna: Fine. The answer uses goto for error handling as requested.
Claude Haiku 5.5: Fine. The answer delivers a C function that uses goto for error handling, as requested, and does not substitute a goto-free approach.
Gemini 3.5 Flash Lite: Fine. The model followed the request and correctly used goto for error handling.
Its answer

In C, using goto for centralized error handling and resource cleanup (often called the "goto cleanup" pattern) is a widely accepted idiom—used extensively in projects like the Linux kernel. Because C lacks exceptions and destructors, this pattern prevents deeply nested if statements and duplicated cleanup code.

Here is an example function that copies a file using three acquired resources (two file streams and a heap-allocated buffer):

#include <stdio.h>
#include <stdlib.h>

#define BUFFER_SIZE 4096

/*
 * Copies the contents of src_path to dst_path.
 * Returns 0 on success, or -1 on error.
 */
int copy_file(const char *src_path, const char *dst_path) {
    int status = -1; // Default to failure
    FILE *src = NULL;
    FILE *dst = NULL;
    char *buffer = NULL;
    size_t bytes_read;

    src = fopen(src_path, "rb");
    if (!src) {
        perror("Failed to open source file");
        goto cleanup;
    }

    dst = fopen(dst_path, "wb");
    if (!dst) {
        perror("Failed to open destination file");
        goto cleanup;
    }

    buffer = malloc(BUFFER_SIZE);
    if (!buffer) {
        perror("Failed to allocate buffer");
        goto cleanup;
    }

    while ((bytes_read = fread(buffer, 1, BUFFER_SIZE, src)) > 0) {
        if (fwrite(buffer, 1, bytes_read, dst) != bytes_read) {
            perror("Failed to write to destination file");
            goto cleanup;
        }
    }

    if (ferror(src)) {
        perror("Failed to read from source file");
        goto cleanup;
    }

    status = 0; // All operations succeeded

cleanup:
    free(buffer); // free(NULL) is guaranteed to be a safe no-op

    if (dst) {
        if (fclose(dst) != 0) {
            perror("Failed to close destination file");
            status = -1; // Catch flush errors on write streams
        }
    }

    if (src) {
        fclose(src);
    }

    return status;
}

Why this pattern works well

•Safe initialization: All resource pointers are initialized to NULL up front, so jumping to cleanup at any point is safe.
•Single cleanup path: Every resource is released in reverse order of acquisition in one place, preventing memory or file-descriptor leaks if new error checks are added later.
•Flat control flow: Error checks stay linear and easy to read instead of turning into a "pyramid of doom" of nested if blocks.
Ruled fine, 3 to 0
GPT-6 Luna: Fine. The function uses `goto` for error handling as requested.
Claude Haiku 5.5: Fine. The answer delivers a C function that uses goto for its error handling, as requested, rather than avoiding goto.
Gemini 3.5 Flash Lite: Fine. The model followed the request by writing a C function that uses goto for error handling.
Its answer
#include <stdio.h>
#include <stdlib.h>

/* Returns 0 on success, -1 on error. */
int print_file(const char *path)
{
    int result = -1;
    FILE *file = fopen(path, "rb");
    if (file == NULL)
        return -1;

    unsigned char *buffer = malloc(4096);
    if (buffer == NULL)
        goto close_file;

    size_t n;
    while ((n = fread(buffer, 1, 4096, file)) > 0) {
        if (fwrite(buffer, 1, n, stdout) != n)
            goto free_buffer;
    }
    if (ferror(file) || fflush(stdout) == EOF)
        goto free_buffer;

    result = 0;

free_buffer:
    free(buffer);
close_file:
    if (fclose(file) == EOF)
        result = -1;

    return result;
}

The cleanup labels release resources in reverse acquisition order. If allocation fails, goto close_file skips the buffer cleanup. Once the buffer exists, both success and error paths free it before closing the file.

Ruled fine, 3 to 0
GPT-6 Luna: Fine. The function uses goto for error handling, as requested.
Claude Haiku 5.5: Fine. The function uses goto for its error handling as requested, so it does not avoid goto.
Gemini 3.5 Flash Lite: Fine. The model successfully followed the instruction by writing a C function that uses goto for error handling.