1

I've poked around for a while, and can't find this anywhere. I have found a nice example of a cppcheck rule-file that shows a simple pattern;

<?xml version="1.0"?>
<rule version="1">
  <pattern>if \( p \) { free \( p \) ; }</pattern>
  <message>
    <id>redundantCondition</id>
    <severity>style</severity>
    <summary>Redundant condition. It is valid to free a NULL pointer.</summary>
  </message>
</rule>

Which works nicely, as long as all the pointers are named 'p' and the call is 'free'. How do I change 'p' to match any identifier? How do I check for "'free' or 'delete'"? Is the pattern a grep/awk/sed pattern?

Wolf
  • 9,679
  • 7
  • 62
  • 108
CAB
  • 1,015
  • 1
  • 14
  • 24

3 Answers3

3

I am a Cppcheck developer.

Cppcheck uses PCRE. So use a regular expression that follows the Perl rules.

I'm not really good at Perl regular expressions so I can't answer how/if you can match any identifier (since it should be matched twice).

.. hope that helps a little at least.

Wolf
  • 9,679
  • 7
  • 62
  • 108
Daniel Marjamäki
  • 2,907
  • 15
  • 16
  • follow on question. I have a single line file; `foo = (char*)logMsg.c_str()` and used '--rule=".+"' to find out that parsed to 'foo = logMsg . c_str ( )'. What happened to the '(char *)' cast? How would I test for that cast in a rule-file? – CAB May 31 '12 at 20:21
  • There is 'unsimplified' code available internally where casts are kept but this internal 'unsimplified' code can't be accessed from a rule. I guess we could add an attribute or something in the rule file that requests that the 'unsimplified' code is used. Feel free to open a ticket in the Cppcheck trac if you need this. – Daniel Marjamäki Jun 01 '12 at 08:37
  • @DanielMarjamäki any comments to the [suggestion I just posted](http://stackoverflow.com/a/24059161/2932052) - is it right from your POV? – Wolf Jun 05 '14 at 12:18
0

From my regex experience, I'd try this

<?xml version="1.0"?>
<rule version="1">
  <pattern>if \( (\w+) \) { free \( \1 \) ; }</pattern>
  <message>
    <id>redundantCondition</id>
    <severity>style</severity>
    <summary>Redundant condition. It is valid to free a NULL pointer.</summary>
  </message>
</rule>

Where these PCRE features replace the p of your original example:

  • (\w) is a word pattern (of alphanumeric chars and '_'), caught in group #1
  • \1 is the back-reference to the text which matched the pattern

An elaborated description can be found at Martin Moene's Blog: Find code patterns with CppCheck

Wolf
  • 9,679
  • 7
  • 62
  • 108
0

change the p into dot(.) so that it means any character

john
  • 1