Skip to content

[Medium] GPhysics dereferences possibly-null physics list before the null check #130

@zhaozhiwen

Description

@zhaozhiwen

GPhysics::build calls physList->RegisterPhysics(...) immediately after factory.GetReferencePhysList(...), before the if (!physList) guard — so an unknown/failed physics-list name causes a null-pointer dereference instead of the intended error.

Affected files

  • gemc/gphysics/gphysics.cc:57-63

Details

physList = factory.GetReferencePhysList(g4physList);

// Register step limiters (module default add-on).
physList->RegisterPhysics(new G4StepLimiterPhysics());   // line 61: deref

if (!physList) { log->error(ERR_PHYSLISTERROR, "physics list <" + gphysList + "> could not be loaded."); }

g4alt::G4PhysListFactory::GetReferencePhysList returns nullptr when the requested list name is not recognized. The code dereferences the result at line 61 (physList->RegisterPhysics) before the null check at line 63. When the name is invalid, this segfaults — the user never sees the intended ERR_PHYSLISTERROR diagnostic. It also leaks the freshly new'd G4StepLimiterPhysics on that path.

Impact

A typo or unsupported physics-list name crashes the program with a raw segfault instead of producing the clear, actionable error message that the code was written to emit.

Proposed fix

Move the null check to immediately after GetReferencePhysList, before any dereference, and only new the add-on once the list is known good.

@@
     physList = factory.GetReferencePhysList(g4physList);
 
+    if (!physList) { log->error(ERR_PHYSLISTERROR, "physics list <" + gphysList + "> could not be loaded."); }
+
     // Register step limiters (module default add-on).
     // This is intentionally registered even when users select a standard reference list.
     physList->RegisterPhysics(new G4StepLimiterPhysics());
-
-    if (!physList) { log->error(ERR_PHYSLISTERROR, "physics list <" + gphysList + "> could not be loaded."); }
 
     log->info(2, "G4PhysListFactory: <" + g4physList + "> loaded.");

If log->error is non-terminating, follow it with a return; so the subsequent physList->RegisterPhysics is not reached on the null path.


Split out from #102 (one issue per bug). Found via an AI-assisted code review with manual verification against commit 5f8ce875.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    Status
    Planned

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions