Segmentation fault when writing particle position to csv file

Hello all,

So my simulation is a modification of the LXe example, and I am attempting to write to a csv file the position at which the primary particle enters/exits a particular physical volume. To do this, I have added the following code to the UserSteppingAction method in LXeSteppingAction.cc:

    if (theTrack->GetParentID() == 0)
    {
        if (thePostPV->GetName() == "scintillator1")
        {
            if (thePrePV->GetName() != "scintillator1")
            {
                CLHEP::Hep3Vector Det1 = theTrack->GetPosition();
                std::cout << Det1[0] << std::endl;
                analysisManager->FillNtupleDColumn(0, 14, Det1[0]);
            }
        }
    }

While this does successfully print the correct position, after the simulation finishes iterating through the rest of the particles but before the event is visualized, I get a segmentation fault and crash. This happens even if I delete either the print line or the csv write line, but if I remove both leaving only the line which gets the track position, I no longer receive the fault. I am new to C++ so this may be a basic programming error, but I haven’t had luck solving the problem on other forums. Any help would be much appreciated!

Geant4 11.1.1
Windows 10 enterprise
Visual Studio 2022
CMake 3.27.1

You should G4cout and G4endl. G4cout is thread safe.

1 Like

Thank you for these suggestions - I will implement them.

Unfortunately this will not solve my problem. I get the same fault even if I remove the cout line entirely.

Another thought…

Det1 is a CLHEP::Hep3Vector. What does Det1[0] mean? The notation implies it’s an array, but it’s not. I’m surprised it compiles. Look for some compilation errors or warnings.

Do you mean you want the x-component? That would be Det1.x().

John

1 Like

@allison Just a side note – Hep3Vector does have operator to access the coordinates by index.

1 Like

My first guess would be if your PostPV is a null pointer?

You could implement print statements after each if statement to see which one causes the fault

1 Like

I think ultimately you’ll have to run the program through a debugger to pinpoint the location and cause. There’s not really enough info here to diagnose properly.

1 Like

Thank you for the suggestion, this was exactly the problem. For reasons unclear to me, it seems like on the final loop of user stepping action the PostPV was a null pointer. Adding an if statement to check at the start fixed the problem. Thank you!

The final step for a lot of track is leaving the world volume. Since there’s nothing outside the world volume, the post-step pointer in that case must be null.

1 Like