terminate called after throwing an instance of std::bad_alloc - c++

I am facing the current error since last few days and fighting with it to resolve the problem but all in vain. I am using Pythia8 and fastjet event generator together and running my simple code. Code compiled nicely but causes run time error as shown below. It runs fine with low events but for large iterations(events) it failed and print the error under discussion:
PYTHIA Warning in SpaceShower::pT2nextQCD: weight above unity
PYTHIA Error in StringFragmentation::fragment: stuck in joining
PYTHIA Error in Pythia::next: hadronLevel failed; try again
PYTHIA Error in SpaceShower::pT2nearQCDthreshold: stuck in loop
PYTHIA Error in StringFragmentation::fragmentToJunction: caught in junction flavour loop
PYTHIA Warning in StringFragmentation::fragmentToJunction: bad convergence junction rest frame
PYTHIA Warning in MultipleInteractions::pTnext: weight above unity
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
here is code:
[
double Rparam = 0.4;
fastjet::Strategy strategy = fastjet::Best;
fastjet::RecombinationScheme recombScheme = fastjet::Et_scheme;
fastjet::JetDefinition *jetDef = NULL;
jetDef = new fastjet::JetDefinition(fastjet::antikt_algorithm, Rparam,
recombScheme, strategy);
// Fastjet input
std::vector <fastjet::PseudoJet> fjInputs;
//================== event selection efficiency variables ==========
int nev=0;
int passedJetCut=0;
int passedBJetCut=0;
int passedLeptonCut=0;
int passedMtaunuCut=0;
int passedMtaunubCut=0;
int passedWCut=0;
int passedTopCut=0;
int passedMetCut=0;
int njets=2;
int nbjets=1;
int ntaus=1;
double MW=80.38;
// Begin event loop. Generate event. Skip if error. List first one.
for (int iEvent = 0; iEvent < HowManyEvents; ++iEvent) {
nev++;
if(iEvent%1000==0)cout<<"Event number "<<iEvent<<endl;
// cout<<"Event number "<<iEvent<<endl;
//==================== PYTHIA ==================
if(!pythia.next())continue;
// if (iEvent<3)pythia.process.list();
if (iEvent<2)pythia.event.list();
//if (iEvent<2)event.list();
//==================== TAUOLA ==================
// Convert event record to HepMC
HepMC::GenEvent * HepMCEvt = new HepMC::GenEvent();
//Conversion needed if HepMC uses different momentum units
//than Pythia. However, requires HepMC 2.04 or higher.
HepMCEvt->use_units(HepMC::Units::GEV,HepMC::Units::MM);
ToHepMC.fill_next_event(pythia, HepMCEvt);
// if (FirstEvent)event.list();
//Beware this does not reflect tauola effect
//tauola C++ interface only affects HepMC::GenEvent which is made
// from pythia.event
//run TAUOLA on the event
TauolaHepMCEvent * t_event = new TauolaHepMCEvent(HepMCEvt);
//Since we let Pythia decay taus, we have to undecay them first.
t_event->undecayTaus();
t_event->decayTaus();
// Reset Fastjet input for each event
fjInputs.resize(0);
// Keep track of missing ET
//*******************
class IsbFromTop {
public:
bool operator()( const HepMC::GenParticle* p ) {
if ( abs(p->pdg_id()) == 5 ) return 1;
return 0;
}
};
vector<bjet> bjets;
bjets.clear();
//======================= loop over particles ========================
for(HepMC::GenEvent::particle_const_iterator p = HepMCEvt->particles_begin();
p!= HepMCEvt->particles_end(); ++p ){
int pid=(*p)->pdg_id();
double pt=(*p)->momentum().perp();
double px=(*p)->momentum().px();
double py=(*p)->momentum().py();
double pz=(*p)->momentum().pz();
double e=(*p)->momentum().e();
double eta=(*p)->momentum().eta();
double phi=(*p)->momentum().phi();
if(abs(pid)==15){
if ( (*p)->production_vertex() ) {
for ( HepMC::GenVertex::particle_iterator mother =
(*p)->production_vertex()->particles_begin(HepMC::parents);
mother!=(*p)->production_vertex()->particles_end(HepMC::parents);
++mother )
{
if(abs((*mother)->pdg_id())==24){
W2Tau=true;
}
}
}
}
// Final state only
if ((*p)->status()!=1)continue;
if(abs(pid)==11 || abs(pid)==13){
if(!FoundLepton){
hleptonet->Fill(pt);
hleptoneta->Fill(eta);
hleptonphi->Fill(phi);
pxlepton=px;
pylepton=py;
pzlepton=pz;
elepton=e;
FoundLepton=true;
}
if(pt>20. && pt<80. && fabs(eta)<1.5)
nleptons++;
}
// No neutrinos
if (abs(pid)==12 ||
abs(pid)==14 ||
abs(pid)==16){nnu++;continue;}
// Only |eta| < 5
if(fabs(eta)>5.)continue;
// Missing ET
mex -= px;
mey -= py;
// Store as input to Fastjhttps://mail.google.com/mail/u/0/?shva=1#inboxet
fjInputs.push_back(fastjet::PseudoJet (px,py,pz,e));
}//loop over particles in the event
continue.............................
thanks a lot for your help
ijaz

Sorry I don't know anything about Pythia but in c++ new Operator will return either allocated memory pointer or it will throw a bad_alloc exception.
Using try catch we can solve this issue-
Like:
while(true)
{
try
{
string s = new string(1024*1024*1024);
break;
}
catch
{
// do stuff
}
}
It will solve the crashing issue but the CPU utilization will go UP until we got the required memory.(and if CPU reach at 100% usage it will hang the system)

Related

Simulating Leach has encounter a problem. Finished with error in omnet++

When running the simulation in omnet++ 5.7 the execution stops suddenly and closes.
This is the code that is being run in omnet
auto simulation = getSimulation();
for (i = 1; i <= simulation->getLastComponentId(); i++) {
int x, y, id;
//scan the simulation module vector
mod = (cModule*)simulation->getModule(i);
if (strcmp(mod->getName(), "node") == 0) {
id = ((Node*)mod)->myId;
x = ((Node*)mod)->xpos;
y = ((Node*)mod)->ypos;
nodePtr[id] = ((Node*)mod);
if (id != this->myId) {
cGate* g;
char gName1[32], gName2[32];
// make new gate here
if (this->hasGate(gName1)) {
this->gate(gName1)->disconnect();
this->deleteGate(gName1);
}
this->addGate(gName1, cGate::OUTPUT, false);
// make new gate at other side
if (mod->hasGate(gName2)) {
mod->gate(gName2)->disconnect();
mod->deleteGate(gName2);
}
mod->addGate(gName2, omnetpp::cGate::INPUT, false);
//CHANNEL
cIdealChannel* ch = NULL;
this->gate(gName1)->connectTo(mod->gate(gName2), ch);
g = this->gate(gName1);
g->setDisplayString(g->getDisplayString());
}
}
}
I assume that the last line g->setDisplayString(g->getDisplayString()); is probably where the code breaks. The code repeats in the for loop with i<= simulation->getLastComponentId(). I'm new to Omnet++. Any suggestion to fix this would be helpful.
Thanks.
Several things in your code may be source of crashing:
getModule(i) may return nullptr, see OMNeT++ Simulation API, so you should check in the code whether result is not nullptr.
gName1 and gName2 are not set!
Other issues:
instead of (Node*)mod use dynamic_cast<Node*)>(mod) and check whether results is not nullptr.
instead of strcmp(mod->getName(), "node") == 0 I advice using mod->isName("node") - see OMNeT++ Simulation API
if you want to obtain a module whose name is "node", you do not need to manually check the name of every module - there is a useful method getModuleByPath() see OMNeT++ Simulation Manual

Segmentation fault(core dumped) in multi threading using boost threads

When try to run my program with up to 1 thread, it works fine for a while (some seconds or minutes) but finally get segmentation fault(core dumped) or double free(faststop ) error.
Here are the function which the threads run.
//used in the Function
[Added] typedef folly::ProducerConsumerQueue<std::string*> PcapTask;
struct s_EntryItem {
Columns* p_packet; //has some arbitrary method and variables
boost::mutex _mtx;
};
//_buffersConnection.wait_and_pop()
Data wait_and_pop() {
boost::mutex::scoped_lock lock(the_mutex);
while (the_queue.empty()) {
the_condition_variable.wait(lock);
}
Data popped_value = the_queue.front();
the_queue.pop();
return popped_value;
}
struct HandlerTask {
std::string year;
folly::ProducerConsumerQueue<std::string*> queue = NULL;
};
-----------------------------------------
//The function which threads run
void Connection() {
std::string datetime, year;
uint32_t srcIPNAT_num, srcIP_num;
std::string srcIP_str, srcIPNAT_str, srcIPNAT_str_hex;
int counter = 0;
while (true) {
//get new task
HandlerTask* handlerTask = _buffersConnection.wait_and_pop();
PcapTask* pcapTask = handlerTask->queue;
year = handlerTask->year;
counter = 0;
do {
pcapTask->popFront();
s_EntryItem* entryItem = searchIPTable(srcIP_num);
entryItem->_mtx.lock();
if (entryItem->p_packet == NULL) {
Columns* newColumn = new Columns();
newColumn->initConnection(srcIPNAT_str, srcIP_str, datetime, srcIP_num);
entryItem->p_packet = newColumn;
addToSequanceList(newColumn);
} else {
bool added = entryItem->p_packet->addPublicAddress(srcIPNAT_str_hex, datetime);
if (added == false) {
removeFromSequanceList(entryItem->p_packet);
_bufferManager->addTask(entryItem->p_packet);
Columns* newColumn = new Columns();
newColumn->initConnection(srcIPNAT_str, srcIP_str, datetime, srcIP_num);
//add to ip table
entryItem->p_packet = newColumn;
addToSequanceList(newColumn);
}
}
entryItem->_mtx.unlock();
++_totalConnectionReceived;
} while (true);
delete pcapTask;
delete handlerTask;
}
}
You can use Valgrind, its very easy. Build your app in debug config and pass program executable to valgrind. It can tell you wide spectre of programming errors occuring in your app in runtime. The price of using Valgrind is that program runs considerably slower (some times tens times slower) than without Valgrind. Specically, for example, Valgrind will tell you where your your programs' memory was free'ed first when it tried to free it second time when it happens.
I'm not sure that it's the problem, but...
Are you sure that you must call delete over pcapTask?
I mean: you delete it but queue in struct HandlerTask is a class member, not a pointer to a class.
Suggestion: try to comment the line
delete pcapTask;
at the end of Connection()
--- EDIT ---
Looking at you added typedef, I confirm that (if I'm not wrong) there is something strange in your code.
pcapTask is defined as a PcapTask pointer, that is a folly::ProducerConsumerQueue<std::string*> pointer; you initialize it with a folly::ProducerConsumerQueue<std::string*> (not pointer)
I'm surprised that you can compile your code.
I think you should, first of all, resolve this antinomy.
p.s.: sorry for my bad English.

Creating new objects in C++ function causes program to crash

I have a program which allows the user to play Dominoes against 3 CPU players, with varying difficulty. Each CPU player can be either Beginner, Intermediate or Expert, and each difficulty has it's own class. If I initiate my 3 CPU players at the beginning of my 'Window' class (below), the program runs fine.
In Window.h
public:
Window(QWidget *parent = 0);
Intermediate *cpu1;
Beginner *cpu2;
Intermediate *cpu3;
In Window.cpp
Window::Window(QWidget *parent):QDialog(parent) {
cpu1 = new Intermediate;
cpu2 = new Beginner;
cpu3 = new Intermediate;
}
However I want the user to be able to select the CPU difficulties at the beginning of the game, so I now have a function within 'Window' that creates the objects. As soon as I call this function the game freezes and I get an error message pop up saying telling me the program has ended unexpectedly.
void Window:: startGame(){
cpu1 = new Intermediate;
cpu2 = new Beginner;
cpu3 = new Intermediate;
}
If anyone would be able to explain to me what is going on and what I can do to get around this that would be great.
Intermediate.cpp (Beginner.cpp is almost identical)
#include "intermediate.h"
Intermediate::Intermediate()
{
tilePlaced = false;
skipGo = false;
}
void Intermediate::findDoubles(int a[7][2]){
for(int i = 0; i < 7; i++){ // Creates new doubles list after each go.
doublesList[i] = 0;
}
for(int i = 0; i < 7; i++){ // Creates a list of doubles
if ((a[i][0] == a[i][1]) && (a[i][0] != 7)){
doublesList[a[i][0]] = 1;
}
}
}
bool Intermediate::addDomino(){} // Function that finds best domino to replace and returns bool
if(tilePlaced == false){
pass++;
text += "\nPassed turn";
return false;
}
else{
pass = 0;
text += QString("\nPlaced [%1 : %2]").arg(a).arg(b);
return true;
}
}
One way to start would be to narrow down which class is causing the fault. Does it work if they are all Beginner, or if they are all Intermediate? If so then the other one is causing the problem.

C++ Debug assertion failed, using Windows.h mutex

I have a problem caused by this code:
char KernelFS::mount(Partition* part) {
WaitForSingleObject(mutexFS,INFINITE);
int pos;
for(pos=0; pos<26; pos++)
if(mountedPartitions[pos] == 0)
break;
if(pos < 26) {
mountedPartitions[pos] = part;
bitVectors[pos] = new BitVector(part);
fileEvidention[pos] = new ListHandler();
openedFiles[pos] = 0;
forbidOpening[pos] = false;
ReleaseMutex(mutexFS);
return intToChar(pos);
}
else {
ReleaseMutex(mutexFS);
return '0';
}
}
and
char KernelFS::format(char part){
WaitForSingleObject(mutexFS,INFINITE);
forbidOpening[charToInt(part)] = true;
ReleaseMutex(mutexFS);
while(openedFiles[charToInt(part)]>0)
WaitForSingleObject(unmountSem,INFINITE);
WaitForSingleObject(mutexFS,INFINITE);
// write fresh bit vector to cluster 0 of partition
bitVectors[charToInt(part)]->formatBitVector();
openedFiles[charToInt(part)] = 0;
forbidOpening[charToInt(part)] = false;
delete fileEvidention; //!!***!!
fileEvidention[charToInt(part)] = new ListHandler();
// some other stuff, irrelevant
ReleaseMutex(mutexFS);
return 1;
}
There are 3 thread executing, 1 is blocked and two are running through this code;
they first call mount, then format (each has its own argument Partition object, p1 and p2).
The first time mount is called, it always goes through - then there is an assertion failure at random during one of the next calls of mount/format by any of the two running threads.
Usually, it fails during thread 1 - it calls mount(..) completes it, then calls format(...) and fails around:
delete fileEvidention[charToInt(pos)];
(in debug mode, when I reach this instruction, even if I try to go into with F11, there is an assertion failure)
In case it matters... this is the initialization:
char KernelFS::firstLetter = 'A'; // 'A' = 65
Partition* KernelFS::mountedPartitions[26] = {0}; // init. no partitions are mounted
BitVector* KernelFS::bitVectors[26] = {0}; // init. no partitions are mounted
bool KernelFS::forbidOpening[26] = {false};
long KernelFS::openedFiles[26] = {0};
ListHandler* KernelFS::fileEvidention[26] = {0};
HANDLE KernelFS::mutexFS = CreateMutex(0,0,0);
HANDLE KernelFS::unmountSem = CreateSemaphore(0,0,INFINITE,0);
I have never had this error before, I have no idea how to debug this nor what could cause it.
Thanks for the help, in advance.
EDIT:
when i remove the marked line of code (and ignore the memory leak) there is no assertion failure. What is this witchcraft ?
! :)
Solved. should be
delete fileEvidention[charToInt(part)];
......

Threads C++, Access Violation reading location x error

Platform : Windows 7
I'm developing a project for known text cipher attack in which;
Main process creates n child processes
Child processes decrypt an encrypted string, key subspace is partitioned according to number of child processes
Communication between child processes are by a static variable
for(int i = 0; i<info.totalNumberOfChildren; i++)
{
startChild( &info.childInfoList[i]);
//_beginthread(startChild, 0, &info.childInfoList[i]);
}
Above code works fine since:
First child starts execution, the key is set as a number such as 8 for testing purposes which is within the first child's partition, so first child finds the key, reports and sets true the killSwitch.
All the other children that are created are closed even before checking the first key as the killSwitch is true.
When I however do this :
for(int i = 0; i<info.totalNumberOfChildren; i++)
{
//startChild( &info.childInfoList[i]);
_beginthread(startChild, 0, &info.childInfoList[i]);
}
I get an access violation error. What could possibly be my source of error ?
Edit: I will try to share as relevant code as I can
startChild does the following:
void startChild( void* pParams)
{
ChildInfo *ci = (ChildInfo*)pParams;
// cout<<"buraya geldi"<<endl;
ChildProcess cp(*ci);
// write to log
cp.completeNextJob();
}
childInfo holds the following :
// header file
class ChildInfo
{
public:
ChildInfo();
ChildInfo(char * encrypted, char * original, static bool killSwitch, int totalNumOfChildren, int idNum, int orjLen);
void getNextJob();
bool keyIsFound();
Des des;
void printTest();
bool stopExecution;
bool allIsChecked;
char * encyptedString;
char * originalString;
int id;
int orjStrLen;
private:
int lastJobCompleted;
int totalNumberOfChildren;
int jobDistBits;
};
completeNextJob() does the following :
void ChildProcess::completeNextJob()
{
cout<<"Child Id : "<<info.id<<endl;
// cout<<"Trying : "<<info.encyptedString<<endl; // here I got an error
char * newtrial = info.encyptedString;
char * cand = info.des.Decrypt(newtrial); // here I also get an error if I comment out
/*
cout<<"Resultant : "<<cand<<endl;
cout<<"Comparing with : "<<info.originalString<<endl;
*/
bool match = true;
for(int i = 0; i<info.orjStrLen; i++)
{
if(!(cand[i] == info.originalString[i]))
match = false;
}
if(match)
{
cout<<"It has been acknowledged "<<endl;
info.stopExecution = true;
return;
}
else
{
if(!info.keyIsFound())
{
if(!info.allIsChecked)
{
info.getNextJob();
completeNextJob();
}
else
{
}
}
else
{
}
}
}
decrypt() method does the following :
char * Des::Decrypt(char *Text1)
{
int i,a1,j,nB,m,iB,k,K,B[8],n,t,d,round;
char *Text=new char[1000];
unsigned char ch;
strcpy(Text,Text1); // this is where I get the error
i=strlen(Text);
keygen();
int mc=0;
for(iB=0,nB=0,m=0;m<(strlen(Text)/8);m++) //Repeat for TextLenth/8 times.
{
for(iB=0,i=0;i<8;i++,nB++)
{
ch=Text[nB];
n=(int)ch;//(int)Text[nB];
for(K=7;n>=1;K--)
{
B[K]=n%2; //Converting 8-Bytes to 64-bit Binary Format
n/=2;
} for(;K>=0;K--) B[K]=0;
for(K=0;K<8;K++,iB++) total[iB]=B[K]; //Now `total' contains the 64-Bit binary format of 8-Bytes
}
IP(); //Performing initial permutation on `total[64]'
for(i=0;i<64;i++) total[i]=ip[i]; //Store values of ip[64] into total[64]
for(i=0;i<32;i++) left[i]=total[i]; // +--> left[32]
// total[64]--|
for(;i<64;i++) right[i-32]=total[i];// +--> right[32]
for(round=1;round<=16;round++)
{
Expansion(); //Performing expansion on `right[32]' to get `expansion[48]'
xor_oneD(round);
substitution();//Perform substitution on xor1[48] to get sub[32]
permutation(); //Performing Permutation on sub[32] to get p[32]
xor_two(); //Performing XOR operation on left[32],p[32] to get xor2[32]
for(i=0;i<32;i++) left[i]=right[i]; //Dumping right[32] into left[32]
for(i=0;i<32;i++) right[i]=xor2[i]; //Dumping xor2[32] into right[32]
} //rounds end here
for(i=0;i<32;i++) temp[i]=right[i]; // Dumping -->[ swap32bit ]
for(;i<64;i++) temp[i]=left[i-32]; // left[32],right[32] into temp[64]
inverse(); //Inversing the bits of temp[64] to get inv[8][8]
/* Obtaining the Cypher-Text into final[1000]*/
k=128; d=0;
for(i=0;i<8;i++)
{
for(j=0;j<8;j++)
{
d=d+inv[i][j]*k;
k=k/2;
}
final[mc++]=(char)d;
k=128; d=0;
}
} //for loop ends here
final[mc]='\0';
char *final1=new char[1000];
for(i=0,j=strlen(Text);i<strlen(Text);i++,j++)
final1[i]=final[j]; final1[i]='\0';
return(final);
}
Windows is trying to tell you why your program crashed. Please use a debugger to see what Windows is talking about. Location X is important: it should tell you whether your program is dereferencing NULL, overflowing a buffer, or doing something else. The call stack at the time of the crash is also very important.
Debugger is your best friend, try to use it and check step by step what could cause this access violation.
I think that info.encyptedString is not initialized correctly and pointing to not allocated memory, but I cant be sure because you didn't show this part of code.
And of course you must protect your shared resources (info) using some synchronization objects like critical section or mutex or semaphore.
I don't know, the basic issue seems pretty straightforward to me. You have multiple threads executing simultaneously, which access the same information via *pParams, which presumably is of type ChildInfo since that's what you cast it to. That info must be getting accessed elsewhere in the program, perhaps in the main thread. This is corrupting something, which may or may not have to do with Text1 or info.id, these errors can often be 'non-local' and hard to debug for this reason. So start mutex-protecting the entire thread (within your initial loop), and then zero in on the critical sections by trial and error, i.e. mutex-protect as small a region of code as you can get away with without producing errors.