Skip to content

fix(c): reduce false positives in double-free and use-after-free rules#3771

Open
MarkLee131 wants to merge 1 commit intosemgrep:developfrom
MarkLee131:fix/memory-rules-false-positives
Open

fix(c): reduce false positives in double-free and use-after-free rules#3771
MarkLee131 wants to merge 1 commit intosemgrep:developfrom
MarkLee131:fix/memory-rules-false-positives

Conversation

@MarkLee131
Copy link
Copy Markdown

This PR fixes #3770, adding the missing exclusions to three C memory safety rules:

  • double-free: Add return exclusion between two free() calls (mutually exclusive cleanup paths), and recognize
    calloc/realloc/strdup as reallocation (previously only malloc)
  • use-after-free: Add calloc/realloc/strdup as recognized reallocation patterns
  • function-use-after-free: Same calloc/realloc/strdup additions

  • semgrep --test c/lang/security/ — 12/12 pass
  • All existing test cases still match; new ok: cases added for each exclusion

@dannytheway
Copy link
Copy Markdown

dannytheway commented Mar 30, 2026

I have accidentally opened a PR with the same fixes, I can close it if yours gets merged, but can I suggest a few changes?

Detection for functions other than malloc can be implemented more elegantly as:

- pattern-not:
          patterns:
            - pattern-inside: |
                free($VAR);
                ...
                $VAR = $ALLOC(...);
                ...
            - metavariable-pattern:
                metavariable: $ALLOC
                pattern-either:
                  - pattern: malloc
                  - pattern: calloc
                  - pattern: strdup

rather than a series of - pattern-not-inside and it should work fine.

Also the original rule will not flag *ptr=something; as vulnerable, so I suggest to add a - pattern: (*$VAR).

PR is #3795, check here for details.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

C memory safety rules (double-free, use-after-free) missing common exclusion patterns cause false positives

2 participants