How can I find volumes in which gammas are generated?

I have been modifying example B1, adding several additional logical volumes and incorporating the physics from TestEM1. I would now like to find out in which volumes gamma particles are generated by checking at each step if a gamma particle is generated. I modified B1SteppingAction as follows:

G4LogicalVolume* volume 
= step->GetPostStepPoint()->GetTouchableHandle()
  ->GetVolume()->GetLogicalVolume();
  
// check if we are in scoring volume
//if (volume != fScoringVolume) return;
G4String volname = volume->GetName();    
G4int ID = step->GetTrack()->GetParentID();
G4String particleName = step->GetTrack()->GetParticleDefinition()->GetParticleName(); 
G4double edepStep = step->GetTotalEnergyDeposit();
fEventAction->AddEdep(edepStep);
if (ID == 1 && particleName == "gamma"){
fEventAction->incrementSteps();
G4cout<<"gamma vol = " << volname << G4endl;

I then try to run the example with this code using a macro that generates 100 primary electrons. The incrementSteps statement counts up the number of gammas in each event. When the 2 lines with volname are commented out the output from the run indicates that 6 gammas are generated, found by filtering the run output with tracking verbose 1. The count is consistent with that. But when these lines are un-commented the program does not indicate any gammas generated.

Am I doing something wrong in attempting to get the volume corresponding to a gamma?

Edit: I think I found my problem. When checking each step for the volume name I was referencing the post step volume name. But in some cases the particle transports to “out of world” as its last step and has no post-step volume. My work-around was to check the volume name at the pre-step state and at least the program doesn’t crash and it seems to provide a reasonable result.

To find the production volume for a secondary, the post-step is usually the right choice, but not always. You may also check the StepStatus of the post step, and if that is fGeomBoundary or fWorldBoundary, then falling back to pre-step makes sense.

Thank you Michael. I was unaware of the ability to check the step status. There is so much to learn about Geant4.