Back to all reviewers

Assert null before access

tree-sitter/tree-sitter
Based on 2 comments
C

When asserting conditions on potentially null pointers, always check for null first before accessing the pointer's properties or members. This prevents segmentation faults and makes null expectations explicit in the code.

Null Handling C

Reviewer Prompt

When asserting conditions on potentially null pointers, always check for null first before accessing the pointer’s properties or members. This prevents segmentation faults and makes null expectations explicit in the code.

Instead of writing assertions that could crash on null pointers:

assert(root->ref_count > 0);  // Crashes if root is NULL

Use a combined assertion that checks null first:

assert(root && root->ref_count > 0);  // Safe and explicit

This pattern serves two purposes: it prevents crashes during debugging when assertions are enabled, and it clearly documents that the code expects the pointer to be non-null. When removing null checks, ensure the underlying assumptions about null safety have actually changed and document why the check is no longer needed.

2
Comments Analyzed
C
Primary Language
Null Handling
Category

Source Discussions