Code crashing while extracting data from ROOT file

While extracting data from root files, my code is crashing every time I seem to run it. Please let me know if there is any particular reason. The code and the entire stack trace is as follows:

#include <TFile.h>
#include <TH1D.h>
#include <TMath.h>

int main()
    // Open the input ROOT files
    TFile* filePx = new TFile("kaon_minus_Px.root", "READ");
    TFile* filePy = new TFile("kaon_minus_Py.root", "READ");
    TFile* filePz = new TFile("kaon_minus_Pz.root", "READ");

    // Get the histograms from the files
    TH1D* hPx = dynamic_cast<TH1D*>(filePx->Get("hPx"));
    TH1D* hPy = dynamic_cast<TH1D*>(filePy->Get("hPy"));
    TH1D* hPz = dynamic_cast<TH1D*>(filePz->Get("hPz"));

    // Create a histogram for the resultant momentum
    TH1D* hResultantP = new TH1D("hResultantP", "Resultant Momentum", 100, 0.0, 1000.0);

    // Loop over the bins of the histograms
    for (Int_t iBin = 1; iBin <= hPx->GetNbinsX(); ++iBin)
        // Get the values from each histogram bin
        Double_t px = hPx->GetBinContent(iBin);
        Double_t py = hPy->GetBinContent(iBin);
        Double_t pz = hPz->GetBinContent(iBin);

        // Calculate the resultant momentum
        Double_t p = TMath::Sqrt(px * px + py * py + pz * pz);

        // Fill the resultant momentum histogram

    // Save the resultant momentum histogram to a ROOT file
    TFile* outFile = new TFile("resultant_momentum.root", "RECREATE");

    // Clean up
    delete filePx;
    delete filePy;
    delete filePz;
    delete hResultantP;

    return 0;

There was a crash.
This is the entire stack trace of all threads:
#0  0x00007f5c8feea45a in __GI___wait4 (pid=30423, stat_loc=stat_loc
entry=0x7ffe40890318, options=options
entry=0, usage=usage
entry=0x0) at ../sysdeps/unix/sysv/linux/wait4.c:30
#1  0x00007f5c8feea41b in __GI___waitpid (pid=<optimized out>, stat_loc=stat_loc
entry=0x7ffe40890318, options=options
entry=0) at ./posix/waitpid.c:38
#2  0x00007f5c8fe50bcb in do_system (line=<optimized out>) at ../sysdeps/posix/system.c:171
#3  0x00007f5c913172d4 in TUnixSystem::StackTrace() () from /home/barishan/root/lib/
#4  0x00007f5c913145e5 in TUnixSystem::DispatchSignals(ESignals) () from /home/barishan/root/lib/
#5  <signal handler called>
#6  0x000056145c7e350d in main ()

ROOT Version: 6
Platform: Ubuntu(Linux)
Compiler: gcc

    delete filePz; // automatically deletes hResultantP, too
    // delete hResultantP;

BTW. A better approach would be:

    gROOT->cd(); // newly created histograms should go here
    TH1D *hResultantP = new TH1D("hResultantP", "Resultant Momentum", 100, 0.0, 1000.0);
    // ...
    delete hResultantP;