Code crashes when writing to a file

I am attempting to read data from a file, create histograms, and write the histograms to a root file. I get a bus error when I attempt to write the histograms, or when I attempt to write the root file. Any ideas?

[code]#include
#include
#include “TH1F.h”
#include “TFile.h”
#include

using namespace std;

int createRootFile()
{
fstream ROCDelay25OutputFile_(“testoutputat44-2.txt”, ios::in);
if(!ROCDelay25OutputFile_.good()){
cout << “could not open the file” << endl;
assert(0);
}
string tmpROC, tmpDelay, tmpString;
int tmp;
float tmpDAC, tmpResult;

ROCDelay25OutputFile_ >> tmp;
const int const_tmp = tmp;
TH1F myHists[const_tmp];
TFile sampleData(“HistsOfDACSettingVsReading2.root”, “recreate”);
sampleData.cd();

for(int i = 0; i < const_tmp; ++i){
ROCDelay25OutputFile_ >> tmpROC;
ROCDelay25OutputFile_ >> tmpDelay;
tmpString = "DAC Values reported by each ROC at delay: " + tmpDelay + "for ROC: " + tmpROC;
myHists[i] = TH1F(tmpROC.c_str(), tmpString.c_str(), 255, -0.5, 254.5);
for(int j = 0; j < 255; ++j){
ROCDelay25OutputFile_ >> tmpDAC;
ROCDelay25OutputFile_ >> tmpResult;
myHists[i].Fill(tmpDAC, tmpResult);
}
myHists[i].Write(); i get a bus error on this line of code.
}

ROCDelay25OutputFile_.close();

sampleData.Write();

return 0;
}[/code]

Hi,

In your code you would need to use an array of TH1F pointer rather than an array of TH1F object. In the following I simplified your code given that you do not need the histogram past one iteration and that the histogram are automatically owned by the current directory (and written by the call to file.Write()):[code]#include
#include
#include “TH1F.h”
#include “TFile.h”
#include

using namespace std;

int createRootFile()
{
fstream ROCDelay25OutputFile_(“testoutputat44-2.txt”, ios::in);
if(!ROCDelay25OutputFile_.good()){
cout << “could not open the file” << endl;
assert(0);
}
string tmpROC, tmpDelay, tmpString;
int tmp;
float tmpDAC, tmpResult;

ROCDelay25OutputFile_ >> tmp;

TFile sampleData(“HistsOfDACSettingVsReading2.root”, “recreate”);

for(int i = 0; i < const_tmp; ++i){
ROCDelay25OutputFile_ >> tmpROC;
ROCDelay25OutputFile_ >> tmpDelay;
tmpString = "DAC Values reported by each ROC at delay: " + tmpDelay + "for ROC: " + tmpROC;
TH1F *hist = new TH1F(tmpROC.c_str(), tmpString.c_str(), 255, -0.5, 254.5);
for(int j = 0; j < 255; ++j){
ROCDelay25OutputFile_ >> tmpDAC;
ROCDelay25OutputFile_ >> tmpResult;
hist->Fill(tmpDAC, tmpResult);
}
}

ROCDelay25OutputFile_.close();

sampleData.Write();

return 0;
}[/code]

Cheers,
Philippe.

thanks!!! worked like a charm. is there any need to delete the histograms since they are new objects?

[quote] is there any need to delete the histograms since they are new objects?[/quote]No need. The histogram are ‘owned’ by the TFile (and will be deleted when the TFile is ‘closed’; See the ‘Object Ownership’ chapter in the User’s Guide.

Cheers,
Philippe