#!/usr/bin/perl # Detect instances of "if (p) free (p);". # Likewise for "if (p != NULL) free (p);". # Exit status is like grep: 0 for no match. 1 for any number. # Note: giving line numbers isn't practical, since I've reset the # input record separator. use strict; use warnings; (my $ME = $0) =~ s|.*/||; { # Use ';' as the input record separator. $/ = ';'; my $found_match = 0; foreach my $file (@ARGV) { open FH, '<', $file or die "$ME: can't open `$file' for reading: $!\n"; while (defined (my $line = )) { if ($line =~ /\b(if\s*\(\s*(\S+?)(?:\s*!=\s*NULL)?\s*\) \s+(?:xmlXPathFreeContext|(?:sexpr_)?free)\s*\(\s*\2\s*\))/sx) { print "$file: $1\n"; $found_match = 1; } } close FH; } exit !$found_match; } my $foo = <<'EOF'; # The above is to *find* them. # This adjusts them, removing the unnecessary "if (p)" part. git ls-files -z --exclude=find-unnecessary-if-before-free |xargs -0 \ perl -0x3b -pi -e 's/\bif\s*\(\s*(\S+?)(?:\s*!=\s*NULL)?\s*\)\s+((?:xmlXPathFreeContext|(?:sexpr_)?free)\s*\(\s*\1\s*\))/$2/s' EOF