22.3. Segmentation Faults
Table of Contents
Understanding Segmentation Faults in ROOT
Segmentation faults are one of the most common and frustrating problems in C++ and ROOT analysis. They indicate that your code tried to access memory it is not allowed to use. In ROOT, this often appears only at runtime and can be triggered by very small mistakes in object handling or pointer use.
Segmentation faults are not ROOT specific, but certain ROOT patterns make them more likely. Learning to recognize and debug them will save you a significant amount of time.
A segmentation fault almost always means: you dereferenced an invalid pointer or reference. Do not ignore it, and do not try to "catch" it with try/catch. You must fix the underlying bug.
Typical Signs of a Segmentation Fault
In a ROOT session or when running a macro, you may see messages such as:
*** Break *** segmentation violationor your program might simply exit with something like:
Segmentation fault (core dumped)
If you run ROOT with debugging symbols (for example using root.exe -l and compiled macros), you might also see a C++ stack trace printed. This shows which functions were called when the crash happened and is your primary starting point for debugging.
When you get a segmentation fault, note:
The command or macro you were running.
The last lines of output before the crash.
The function names and line numbers in any stack trace.
These clues will help you locate the faulty code.
Common ROOT Specific Causes
Segmentation faults can have many generic C++ causes, but in ROOT analysis code some patterns show up again and again. Understanding these will make it much easier to diagnose crashes.
Using Uninitialized or Null Pointers
The most frequent cause is dereferencing an uninitialized pointer, or a pointer that has become null. For example:
TH1F *h;
h->Fill(1.0); // Segmentation fault: h was never created
Here h contains an undefined value. ROOT cannot check that for you, so the program crashes when Fill tries to access memory through h.
Similarly:
TFile *f = TFile::Open("data.root");
TH1F *h = (TH1F*)f->Get("hist");
// If "hist" does not exist, h will be null
h->Draw(); // Segmentation fault if h == nullptr
If the object does not exist in the file, Get returns nullptr, and calling a method on it causes a crash.
You must always ensure that pointers are initialized before use, and always check the result of functions that can return null.
if (!ptr) {
// Handle error: object was not created or not found
}
Important rule: Before calling a method on a pointer, check that it is non null:
Do not assume Get, FindObject, or similar functions always succeed.
Using Objects After Their Owner Was Deleted
ROOT has an object ownership model. Many objects live inside other objects such as files, directories, or canvases. If the owner is deleted or closed, the contained objects are often deleted too. Using a pointer to such an object after its owner is gone is a classic way to produce a segmentation fault.
Example:
TH1F *h;
{
TFile f("data.root");
h = (TH1F*)f.Get("hist");
} // f goes out of scope and is closed, possibly deleting h
h->Draw(); // Segmentation fault: h points to deleted memorySimilarly, if you create a histogram on a canvas or inside a local scope and it is owned and deleted by ROOT, your pointer becomes invalid.
You must understand which object owns which, and keep owners alive as long as you need the contained objects.
Stack Objects Returning Pointers
Sometimes ROOT functions return pointers to objects that are allocated on the stack or have a shorter lifetime than you expect. This is less common in modern ROOT code but still appears in user macros.
For example:
TH1F* CreateHist() {
TH1F h("h", "hist", 100, 0, 1);
return &h; // Returns pointer to local object
} // h is destroyed here
TH1F* h = CreateHist();
h->Draw(); // Segmentation fault: h points to destroyed object
The object h only existed inside CreateHist. After the function returns, the pointer refers to invalid memory.
ROOT itself usually returns heap allocated objects, but your own helper functions must be written carefully to avoid returning pointers to temporary objects.
Accessing Arrays Out of Bounds
Segmentation faults also arise from C style arrays or std::vector misuse. Even if vectors often perform bounds checks in debug tools, normal C++ will not protect you.
Examples:
double x[10];
x[10] = 1.0; // Valid indices are 0..9, this is out of boundsor with a vector:
std::vector<double> v(5);
v[5] = 3.0; // Valid indices are 0..4, out of boundsThese bugs may crash immediately or may corrupt memory silently and crash later in a completely different part of the code, which is very hard to debug.
In ROOT, such mistakes are common when filling arrays that are then passed to TGraph, TH1, or user functions, especially inside event loops.
TTree Branch Address Mistakes
When working with TTrees, errors in branch addresses are a very common source of segmentation faults. This has its own chapter, but a few specific patterns are worth mentioning here.
Two typical mistakes:
Using a local variable for SetBranchAddress that goes out of scope:
void bad() {
TTree *t = ...;
double value;
t->SetBranchAddress("x", &value);
} // value is destroyed here
// Later in code:
t->GetEntry(0); // Segmentation fault when ROOT writes into &valueOr giving a pointer with the wrong type or not properly allocated:
int *arr = nullptr;
t->SetBranchAddress("arrBranch", arr); // Wrong, missing & and allocation
t->GetEntry(0); // ROOT writes into null, segmentation faultIn both cases ROOT tries to write data into memory that is not valid. The crash might not happen on the first entry, which can make it more confusing.
Mixing Interpreted and Compiled Code Incorrectly
ROOT allows both interpreted C++ (via Cling) and compiled code. If you define functions or classes twice, or change a class definition without recompiling and reloading correctly, you can end up with inconsistent types and invalid memory access.
Examples include:
Redefining a class in the interpreter while also having a compiled version loaded.
Using gSystem->Load and then redefining a function in the interpreter with the same name and different signature.
Passing pointers of one version of a class to functions that were compiled with another version.
These situations can lead to subtle memory layout mismatches and segmentation faults when functions read or write fields at the wrong offsets.
Strategies to Debug Segmentation Faults in ROOT
Resolving a segmentation fault is a systematic process. Guessing is almost always slower than a structured approach.
Step 1: Make the Crash Reproducible and Minimal
First, isolate the problem. Try to:
Run the macro or script with the same inputs until the crash appears consistently.
Strip out parts of the code that are not needed to trigger the crash.
Reduce your code to the smallest version that still crashes. Often this process alone reveals the bug.
Keep a copy of the original full code somewhere safe, then work on a duplicate that you simplify step by step.
Step 2: Read the Stack Trace
When ROOT prints a stack trace, examine it carefully. You might see something like:
#0 0x00007f... in TH1F::Fill(double) from libHist.so
#1 0x00007f... in MyAnalysisFunction() from mymacro_C.so
#2 0x00007f... in main () from root.exe
The important part is usually the first function in your own code, for example MyAnalysisFunction. Look at the line numbers or at least the function name, and go directly to that location in your source.
If the stack trace only shows ROOT internals, the problem is still usually in your code, but the internal ROOT call is where the invalid pointer was used. Look for any object you passed into that ROOT function.
Step 3: Add Defensive Checks in Your Code
A very effective method is to add explicit checks for null pointers, invalid indices, and unexpected conditions.
For example, if you suspect a histogram pointer:
if (!h) {
std::cout << "Histogram h is null, cannot draw" << std::endl;
return;
}
h->Draw();Or for a TTree branch:
if (!branch) {
std::cout << "Branch x not found" << std::endl;
return;
}In event loops, you can print the entry number just before operations that are likely to cause trouble:
for (Long64_t i = 0; i < nentries; ++i) {
std::cout << "Processing entry " << i << std::endl;
t->GetEntry(i);
// ...
}If the program crashes after printing a certain entry number, you know where to focus.
Whenever you get a segmentation fault and see a pointer being used, add a null check before the usage and print a clear error message. If the message appears instead of a crash, you have found at least one part of the problem.
Step 4: Use a Debugger (gdb or lldb)
For more complicated crashes, a real debugger is extremely helpful.
To use gdb with ROOT:
Compile your macro with debugging symbols, for example using +g:
root -l mymacro.C+g
Then run ROOT under gdb:
gdb --args root -l mymacro.C+
Inside gdb, type:
runWhen the segmentation fault occurs, you can type:
btto see the backtrace, and:
frame 0
(or another frame number) to inspect local variables. Commands like print h or print *h show the value of pointers at the crash point.
On macOS you might use lldb instead, with similar commands.
Even a single session with a debugger often reveals immediately that a pointer is null or points to unexpected data.
Step 5: Check Ownership and Lifetime
If the crash appears late in your program, or only when you draw or access some object that was created much earlier, suspect an ownership or lifetime problem.
Ask yourself:
Who owns this object?
Is it created on the stack or heap?
If it lives in a TFile or a TDirectory, is the file still open?
If it lives in a TCanvas or a pad, has that canvas been closed or deleted?
You can often fix such problems by:
Allocating objects on the heap with new and managing them yourself.
Using smart pointers in more advanced C++ projects.
Avoiding returning pointers or references to local variables.
Keeping the parents (files, canvases, directories) in scope as long as their children are needed.
Step 6: Verify Array and Vector Indexes
If your code uses arrays or std::vector, double check every indexing operation, especially inside loops.
Replace unguarded operator[] with at() during debugging:
v.at(i) = value;
at() performs bounds checking and throws an exception when the index is invalid. While this does not prevent all memory errors, it can quickly pinpoint out of range access during development.
For C style arrays, explicitly assert on indices:
assert(i >= 0 && i < N);
arr[i] = value;You can disable assertions in optimized builds later if needed.
Preventing Segmentation Faults in ROOT Code
Once you understand the typical causes and how to debug them, you should write code that avoids them in the first place.
Always Initialize Pointers and Check Results
Declare pointers with a clear initial value:
TH1F *h = nullptr;After calling any ROOT function that can fail, check the returned pointer:
h = (TH1F*)f->Get("hist");
if (!h) {
std::cerr << "Error: histogram 'hist' not found in file" << std::endl;
return;
}Do not continue with analysis if crucial objects are missing or null.
Prefer Objects by Value Where Possible
In many places, you can avoid pointers altogether:
TH1F h("h", "hist", 100, 0, 1);
h.Fill(0.5);
h.Draw();
Here h is an object, not a pointer, and cannot be null. As long as the scope is correct, this pattern is safer. Use pointers only when you really need dynamic lifetime or ROOT ownership behavior.
Keep TFiles and TTrees Alive While You Use Their Contents
If you obtain objects from a TFile or a TTree, ensure that the file remains open and the tree remains valid for the entire period you use the objects. Do not do this:
TH1F* GetHist() {
TFile f("data.root");
return (TH1F*)f.Get("hist");
}Instead, either:
Keep the TFile alive outside:
TFile f("data.root");
TH1F *h = (TH1F*)f.Get("hist");
h->Draw();
// f stays in scope hereor detach the histogram from the file if appropriate:
TFile f("data.root");
TH1F *h = (TH1F*)f.Get("hist");
h->SetDirectory(nullptr); // Detach from file ownership
f.Close();
h->Draw(); // h is now independent
Detaching with SetDirectory(nullptr) is useful when you want the histogram to survive after the file is closed, but remember that you are now responsible for deleting it in more advanced code.
Be Careful With TTree Branch Addresses
When using SetBranchAddress, make sure that:
The variables you pass exist for the entire time you use the TTree.
You pass the correct types and correct levels of indirection.
For simple types and small examples:
double x;
t->SetBranchAddress("x", &x);
for (Long64_t i = 0; i < t->GetEntries(); ++i) {
t->GetEntry(i);
// use x
}Do not use local variables that will be destroyed before the loop finishes.
For branches with variable length arrays or vectors, follow the patterns recommended in the TTree chapters and examples. Incorrect addresses often lead to writes into invalid memory and segmentation faults.
Avoid Redefining Classes in the Interpreter
When you start mixing compiled code and interpreted definitions, be disciplined:
If you have a class in a compiled library or macro, avoid redefining it in the interpreter.
If you change a class definition, recompile and reload the code instead of trying to redefine it on the fly.
Use root-config --cflags and --libs and standard build systems in larger projects to keep compiled code consistent.
This reduces the chance of subtle type mismatches that could cause segmentation faults when reading or writing object data.
Summary
Segmentation faults indicate serious memory access errors. In ROOT analysis, they almost always come from:
Using uninitialized or null pointers.
Using objects after their owner (file, directory, canvas, or local scope) has been destroyed.
Array or vector index errors.
Incorrect TTree branch addresses or lifetimes.
Inconsistent or conflicting class definitions between interpreted and compiled code.
The key habits that prevent and fix these problems are:
Initialize all pointers and check them before use.
Understand ROOT ownership and object lifetime, and keep owner objects alive.
Write small, testable analysis functions and use debug prints strategically.
Use debuggers to inspect crashes rather than guessing.
Be strict and careful with TTree branch setup.
By applying these practices, segmentation faults will become much rarer and much easier to resolve when they do occur.
Views: 0
Where to Move
Move chapter:
- ☰ 1. Introduction to ROOT
- ☰ 1.1. What Is ROOT?
- ☰ 1.2. Installing ROOT
- ☰ 1.3. Starting ROOT
- ☰ 1.4. Your First ROOT Session
-
- ☰ 2. C++ Basics for ROOT
- ☰ 2.1. Why ROOT Uses C++
- ☰ 2.2. Variables and Data Types
- ☰ 2.3. Operators
- ☰ 2.4. Conditional Statements
- ☰ 2.5. Loops
- ☰ 2.6. Functions
- ☰ 2.7. Arrays and Vectors
-
- ☰ 3. ROOT Macros
- ☰ 3.1. What Is a ROOT Macro?
- ☰ 3.2. Running ROOT Macros
- ☰ 3.3. Functions Inside ROOT Macros
- ☰ 3.4. Compiling ROOT Macros
- ☰ 3.5. Organizing a ROOT Project
-
- ☰ 4. ROOT Objects and the ROOT Object Model
- ☰ 4.1. Introduction to ROOT Classes
- ☰ 4.2. Object Names and Titles
- ☰ 4.3. ROOT Collections
- ☰ 4.4. Inspecting ROOT Objects
-
- ☰ 5. Histograms
- ☰ 5.1. Introduction to Histograms
- ☰ 5.2. Creating a 1D Histogram
- ☰ 5.3. Filling Histograms
- ☰ 5.4. Drawing Histograms
- ☰ 5.5. Histogram Properties
- ☰ 5.6. Accessing Histogram Bins
- ☰ 5.7. Histogram Errors
- ☰ 5.8. Normalizing Histograms
- ☰ 5.9. Combining Histograms
-
- ☰ 6. Two-Dimensional Histograms
- ☰ 6.1. Creating 2D Histograms
- ☰ 6.2. Filling 2D Histograms
- ☰ 6.3. Drawing 2D Histograms
- ☰ 6.4. Projections
- ☰ 6.5. Profiles
-
- ☰ 7. Graphs
- ☰ 7.1. Introduction to TGraph
- ☰ 7.2. Creating a TGraph
- ☰ 7.3. Graph Styling
- ☰ 7.4. TGraphErrors
- ☰ 7.5. TGraphAsymmErrors
- ☰ 7.6. MultiGraph
-
- ☰ 8. Canvases and Plotting
- ☰ 8.1. TCanvas
- ☰ 8.2. Dividing a Canvas
- ☰ 8.3. Drawing Multiple Objects
- ☰ 8.4. Legends
- ☰ 8.5. Text and Annotations
- ☰ 8.6. Logarithmic Axes
- ☰ 8.7. Saving Plots
-
- ☰ 9. Styling ROOT Plots
- ☰ 9.1. ROOT Plot Styles
- ☰ 9.2. Axis Configuration
- ☰ 9.3. Line Styles
- ☰ 9.4. Marker Styles
- ☰ 9.5. Publication-Quality Figures
-
- ☰ 10. Mathematical Functions
- ☰ 10.1. Introduction to TF1
- ☰ 10.2. Built-in Functions
- ☰ 10.3. Custom Functions
- ☰ 10.4. Evaluating Functions
- ☰ 10.5. Function Integrals
-
- ☰ 11. Curve Fitting
- ☰ 11.1. Introduction to Fitting
- ☰ 11.2. Gaussian Fits
- ☰ 11.3. Polynomial Fits
- ☰ 11.4. Custom Fit Functions
- ☰ 11.5. Fit Parameters
- ☰ 11.6. Goodness of Fit
- ☰ 11.7. Fit Residuals
- ☰ 11.8. Fitting Graphs
-
- ☰ 12. ROOT Files
- ☰ 12.1. Introduction to ROOT Files
- ☰ 12.2. Creating ROOT Files
- ☰ 12.3. Writing Objects
- ☰ 12.4. Reading ROOT Files
- ☰ 12.5. Exploring ROOT Files
- ☰ 12.6. Directories Inside ROOT Files
-
- ☰ 13. TTrees
- ☰ 13.1. Introduction to TTrees
- ☰ 13.2. Creating a TTree
- ☰ 13.3. Filling a TTree
- ☰ 13.4. Writing a TTree to a File
- ☰ 13.5. Reading a TTree
- ☰ 13.6. Inspecting TTrees
- ☰ 13.7. Drawing Data from TTrees
- ☰ 13.8. Applying Selection Cuts
- ☰ 13.9. Branch Addresses
-
- ☰ 14. Event-Based Data Analysis
- ☰ 14.1. Understanding Event Data
- ☰ 14.2. Event Loops
- ☰ 14.3. Event Selection
- ☰ 14.4. Derived Quantities
- ☰ 14.5. Analysis Workflow
-
- ☰ 15. Working with Real Experimental Data
- ☰ 15.1. Importing Text Data
- ☰ 15.2. Converting Data to ROOT
- ☰ 15.3. Data Cleaning
- ☰ 15.4. Data Calibration
- ☰ 15.5. Signal and Background
-
- ☰ 16. Random Numbers and Simulations
- ☰ 16.1. Random Number Generation
- ☰ 16.2. Common Distributions
- ☰ 16.3. Simple Monte Carlo Simulation
- ☰ 16.4. Detector Resolution Simulation
- ☰ 16.5. Efficiency Simulation
-
- ☰ 17. Statistical Analysis with ROOT
- ☰ 17.1. Basic Statistics
- ☰ 17.2. Probability Distributions
- ☰ 17.3. Statistical Uncertainties
- ☰ 17.4. Chi-Square Tests
- ☰ 17.5. Confidence Intervals
-
- ☰ 18. Modern ROOT with RDataFrame
- ☰ 18.1. Introduction to RDataFrame
- ☰ 18.2. Loading Data
- ☰ 18.3. Filtering Data
- ☰ 18.4. Defining New Columns
- ☰ 18.5. Creating Histograms
- ☰ 18.6. Statistical Operations
- ☰ 18.7. Saving Results
- ☰ 18.8. Multithreading
-
- ☰ 19. ROOT and Python
- ☰ 19.1. Introduction to PyROOT
- ☰ 19.2. ROOT Objects in Python
- ☰ 19.3. Reading ROOT Files with Python
- ☰ 19.4. PyROOT and NumPy
- ☰ 19.5. PyROOT and Matplotlib
- ☰ 19.6. Choosing Between C++ and Python
-
- ☰ 20. Advanced TTree Techniques
- ☰ 20.1. Trees with Multiple Branches
- ☰ 20.2. Storing std::vector Objects
- ☰ 20.3. TChain
- ☰ 20.4. Friends
- ☰ 20.5. Efficient TTree Analysis
-
- ☰ 21. ROOT for Particle and Nuclear Physics
- ☰ 21.1. Four-Vectors
- ☰ 21.2. Particle Kinematics
- ☰ 21.3. Invariant Mass
- ☰ 21.4. Angular Distributions
- ☰ 21.5. Detector Spectra
-
- ☰ 22. Debugging and Common ROOT Problems
- ☰ 22.1. ROOT Object Ownership
- ☰ 22.2. Null Pointers
- ☰ 22.3. Segmentation Faults
- ☰ 22.4. Missing Histograms
- ☰ 22.5. ROOT File Problems
- ☰ 22.6. TTree Branch Problems
- ☰ 22.7. Histogram Range Problems
- ☰ 22.8. Fit Failures
- ☰ 22.9. Debugging ROOT Macros
-
- ☰ 23. Writing Better ROOT Analysis Code
- ☰ 23.1. Separating Analysis and Plotting
- ☰ 23.2. Using Functions
- ☰ 23.3. Using Header Files
- ☰ 23.4. Naming Conventions
- ☰ 23.5. Avoiding Hard-Coded Values
- ☰ 23.6. Configuration Parameters
- ☰ 23.7. Reproducible Analysis
- ☰ 23.8. Version Control with Git
-
- ☰ 24. Final Project
- ☰ 24.1. Project Overview
- ☰ 24.2. Analyze a complete scientific dataset using ROOT.
- ☰ 24.3. Import the Data
- ☰ 24.4. Explore the Dataset
- ☰ 24.5. Apply Data Selection
- ☰ 24.6. Create Histograms
- ☰ 24.7. Fit the Data
- ☰ 24.8. Calculate Physical Quantities
- ☰ 24.9. Estimate Statistical Uncertainties
- ☰ 24.10. Create Publication-Quality Figures
- ☰ 24.11. Save the Analysis Results
- ☰ 24.12. Write a Short Analysis Report
-
- ☰ 25. Appendices
- ☰ 25.1. A. ROOT Command Cheat Sheet
- ☰ 25.2. B. ROOT Histogram Classes
- ☰ 25.3. C. ROOT Graph Classes
- ☰ 25.4. D. Common TTree Commands
- ☰ 25.5. E. Common Drawing Options
- ☰ 25.6. F. Common Fit Functions
- ☰ 25.7. G. ROOT C++ Cheat Sheet
- ☰ 25.8. H. PyROOT Cheat Sheet
- ☰ 25.9. I. Common ROOT Errors and Solutions
- ☰ 25.10. J. Recommended ROOT Analysis Workflow
-
Comments
Please login to add a comment.
Don't have an account? Register now!