Segmentation fault while trying to add histograms

#include <TFile.h>
#include <TH2F.h>
#include <TCanvas.h>
#include <iostream>
#include <TSystem.h>

void addhist() {
    // Create a canvas to display the histograms
    TCanvas *canvas = new TCanvas("canvas", "Combined 2D Histograms", 1000, 800);
    canvas->SetRightMargin(0.15);
    canvas->SetLeftMargin(0.15);

    // Define the directories
    std::vector<std::string> directories = {
        "path/to/file1/",
        "path/to/file2/",
        "path/to/file3/",
        "path/to/file4/",
        "path/to/file5/"
    };

    // Create a pointer to the combined histogram
    TH2F *combinedHist = nullptr;

    for (const auto &dir : directories) {
        // List all files in the directory
        TSystemDirectory sysDir(dir.c_str(), dir.c_str());
        TList *files = sysDir.GetListOfFiles();

        if (files) {
            TSystemFile *file;
            TString fname;
            TIter next(files);

            while ((file = (TSystemFile *)next())) {
                fname = file->GetName();
                if (!file->IsDirectory() && fname.EndsWith(".root")) {
                    // Construct the full file path
                    std::string filePath = dir + fname.Data();

                    // Open the ROOT file
                    TFile *rootFile = new TFile(filePath.c_str(), "READ");
                    if (rootFile->IsOpen()) {
                        // Retrieve the histogram
                        TH2F *hist = (TH2F *)rootFile->Get("2DHist");
                        if (hist) {
                            // Combine the histograms by adding them
                            if (!combinedHist) {
                                combinedHist = static_cast<TH2F *>(hist->Clone());
                            } else {
                                combinedHist->Add(hist);
                            }
                        } else {
                            std::cerr << "Failed to retrieve histogram from file: " << filePath << std::endl;
                        }

                        // Close the ROOT file
                        rootFile->Close();
                    } else {
                        std::cerr << "Failed to open file: " << filePath << std::endl;
                    }
                }
            }
        }
    }

    if (combinedHist) {
        // Draw the combined histogram
        combinedHist->Draw("colz");

        // Save the combined histogram to a ROOT file
        TFile *outputFile = new TFile("output.root", "RECREATE");
        combinedHist->Write();
        outputFile->Close();
    } else {
        std::cerr << "No valid histograms to combine." << std::endl;
    }
}

I have this code to search for root files in 5 directories and add their histograms together and save it in a new root file. It keeps giving me segmentation fault and without more information, I am not able to fix it.
I wrote a dummy version of the above code which takes just 5 root files (one from each directory) and adds their histogram that works but when I want to do that for every root file in those directories, the program keeps failing

This is the code that works.

#include <TFile.h>
#include <TH2F.h>
#include <TCanvas.h>

void addhist() {
    // Create a canvas to display the histograms
    TCanvas *canvas = new TCanvas("canvas", "Combined 2D Histograms", 1000, 800);
    canvas->SetRightMargin(0.15);
    canvas->SetLeftMargin(0.15);

    // Open the ROOT file containing the histograms
    TFile *file1 = new TFile("path/to/file1/file.root");  
    TFile *file2 = new TFile("path/to/file2/file.root");
    TFile *file3 = new TFile("path/to/file3/file.root");
    TFile *file4 = new TFile("path/to/file4/file.root");
    TFile *file5 = new TFile("path/to/file5/file.root");

    // Create pointers to 2D histograms
    TH2F *hist1 = (TH2F*)file1->Get("2Dhist");  // Replace "hist1" with the actual histogram name
    TH2F *hist2 = (TH2F*)file2->Get("2Dhist");  // Replace "hist2" with the actual histogram name
    TH2F *hist3 = (TH2F*)file3->Get("2Dhist");  // Replace "hist3" with the actual histogram name
    TH2F *hist4 = (TH2F*)file4->Get("2Dhist");  // Replace "hist4" with the actual histogram name
    TH2F *hist5 = (TH2F*)file5->Get("2Dhist");  // Replace "hist5" with the actual histogram name

    // Combine the histograms by adding them
    hist1->Add(hist2);
    hist1->Add(hist3);
    hist1->Add(hist4);
    hist1->Add(hist5);
	// Save the combined histogram to a ROOT file
    TFile *outputFile = new TFile("output.root", "RECREATE");
    hist1->Write();
    outputFile->Close();
}

Any help in figuring out why the seg fault shows up would be great

Hi @rushabhgala,
I believe the problem is the way in which you’re declaring combinedHist; try to use TH2F *combinedHist = new TH2F(); instead of TH2F *combinedHist = nullptr;.

Cheers,
Monica

I tried that and modified the code to make the output root file a 3D histogram. While it works without a seg fault I get this error. Is there no way to increase the byte count limit?

Error in TBufferFile::WriteByteCount: bytecount too large (more than 1073741822)
Error in TRint::HandleTermInput(): std::bad_alloc caught: std::bad_alloc

Seems like: Crash when writing canvas to TFile
and [RF] RooDataSet conversion to TTree fails for large datasets (bytecount too large) · Issue #12710 · root-project/root · GitHub

right @moneta ?

Yes, this should be what is giving you the problem

Lorenzo