# Segmentation fault while trying to add histograms

**URL:** <https://root-forum.cern.ch/t/segmentation-fault-while-trying-to-add-histograms/58017>\
**Category:** Newbie\
**Tags:** hist, root\
**Created:** [January 31, 2024, 10:57pm UTC](https://root-forum.cern.ch/t/segmentation-fault-while-trying-to-add-histograms/58017 "2024-01-31T22:57:17Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![rushabhgala](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/rushabhgala/32/23027_2.png) [@rushabhgala](https://root-forum.cern.ch/u/rushabhgala)\
**Post date:** [January 31, 2024, 10:57pm UTC](https://root-forum.cern.ch/t/segmentation-fault-while-trying-to-add-histograms/58017/1 "2024-01-31T22:57:17Z")

</div>

```auto
#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.

```auto
#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

---

<div class="post-metadata">

**Author:** ![mdessole](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/mdessole/32/34021_2.png) [@mdessole](https://root-forum.cern.ch/u/mdessole)\
**Post date:** [February 1, 2024, 1:38pm UTC](https://root-forum.cern.ch/t/segmentation-fault-while-trying-to-add-histograms/58017/2 "2024-02-01T13:38:47Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![rushabhgala](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/rushabhgala/32/23027_2.png) [@rushabhgala](https://root-forum.cern.ch/u/rushabhgala)\
**Post date:** [February 1, 2024, 3:00pm UTC](https://root-forum.cern.ch/t/segmentation-fault-while-trying-to-add-histograms/58017/3 "2024-02-01T15:00:49Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![ferhue](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/ferhue/32/29462_2.png) [@ferhue](https://root-forum.cern.ch/u/ferhue)\
**Post date:** [February 1, 2024, 4:38pm UTC](https://root-forum.cern.ch/t/segmentation-fault-while-trying-to-add-histograms/58017/4 "2024-02-01T16:38:38Z")

</div>

Seems like: [Crash when writing canvas to TFile](https://root-forum.cern.ch/t/crash-when-writing-canvas-to-tfile/58010)  
and [[RF] RooDataSet conversion to TTree fails for large datasets (bytecount too large) · Issue #12710 · root-project/root · GitHub](https://github.com/root-project/root/issues/12710)

right @moneta ?

---

<div class="post-metadata">

**Author:** ![moneta](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/moneta/32/19423_2.png) [@moneta](https://root-forum.cern.ch/u/moneta)\
**Post date:** [February 2, 2024, 12:57pm UTC](https://root-forum.cern.ch/t/segmentation-fault-while-trying-to-add-histograms/58017/5 "2024-02-02T12:57:45Z")

</div>

Yes, this should be what is giving you the problem

Lorenzo
