Skip to content

Fix double-free when output files alias stdout or each other #17

@pvinci

Description

@pvinci

Problem

When block_out_file or serial_out_file default to stdout or point to the same FILE*, the cleanup code in main.c:430-435 causes double-free:

Double-Free Fix Details:

File: src/main.c (lines 430-435)

Problem:
The code was calling fclose() on file handles that might be stdout, stderr, or duplicated file pointers, causing double-free crashes when the same FILE* was closed multiple times.

The Fix:

  // BEFORE (would double-free):
  fclose(args.block_out_file);
  fclose(args.step_out_file);
  fclose(args.serial_out_file);
  // AFTER (prevents double-free):
  if (args.block_out_file != stdout && args.block_out_file != args.serial_out_file)
      fclose(args.block_out_file);
  if (args.step_out_file != stderr)
      fclose(args.step_out_file);
  if (args.serial_out_file != stdout && args.serial_out_file != args.block_out_file)
      fclose(args.serial_out_file);

Why it caused double-free:

  • If block_out_file == stdout, closing it would free stdout
  • Then closing serial_out_file (also potentially stdout) would free it again → crash
  • Same issue if block_out_file == serial_out_file (same pointer, closed twice)

The checks prevent:

  1. Closing standard streams (stdout, stderr)
  2. Closing the same FILE* pointer multiple times when file handles alias each other

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions