Skip to content

Commit

Permalink
cmp: check length off-by-one (#450)
Browse files Browse the repository at this point in the history
* $checklength is the maximum offset in buffer to check which byte(s) in the 2 buffers are not equal
* The subsequent loop is from 0 to $checklength, so avoid potentially accessing $bytes1[$chunk_size]
* If $read_in1 and $read_in2 are equal to $chunk_size, the value of $checklength is not decremented
* Calculate minimum of $read_in1 and $read_in2 (these will never exceed $chunk_size), then decrement by 1
  • Loading branch information
mknos authored Feb 11, 2024
1 parent 8edad69 commit cba333a
Showing 1 changed file with 3 additions and 6 deletions.
9 changes: 3 additions & 6 deletions bin/cmp
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ use strict;

use File::Basename qw(basename);
use Getopt::Std qw(getopts);
use List::Util qw(min);

use constant EX_SUCCESS => 0;
use constant EX_DIFFERENT => 1;
Expand Down Expand Up @@ -174,12 +175,8 @@ if ($skip2) {
READ: while (defined ($read_in1 = sysread $fh1, $buffer1, $chunk_size)) {
$read_in2 = sysread $fh2, $buffer2, $chunk_size;

my $checklength = $chunk_size;
if ($read_in1 < $chunk_size or $read_in2 < $chunk_size) {
$checklength = ( $read_in1 < $read_in2 ?
$read_in1 :
$read_in2 ) - 1;
}
my $checklength = min($read_in1, $read_in2);
$checklength-- if $checklength;

if ($buffer1 ne $buffer2) {
my @bytes1 = unpack 'C*', $buffer1;
Expand Down

0 comments on commit cba333a

Please sign in to comment.