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.
Related
Context
The context of the problem is that I am currently writing a small library for use with the Arduino in order to act as a game controller. The problem I am encountering has more to do with C++ than anything Arduino specific however.
I've included the libraries' header and source code below, followed by the Arduino code. I've truncated it where possible.
Problem
In short, only the last switch / action I define actually gets properly handles.
These actions get defined in the Arduino setup function. For example:
controller.addSwitchContinuous(10, 0); // Pin 10; btn index 0
means that pin 10 gets mapped to button 0. When pin 10 is switched closed this is treated as the button being pressed. This works fine for a single action but when I start adding more only the last action actually works. So in the following example only pin 9 is recognized:
controller.addSwitchContinuous(10, 0); // <-- Doesn't work
controller.addSwitchContinuous(9, 1); // <-- Works
This goes for any arbitrary number of actions:
controller.addSwitchContinuous(10, 0); // <-- Doesn't work
controller.addSwitchContinuous(9, 1); // <-- Doesn't work
controller.addSwitchContinuous(8, 2); // <-- Doesn't work
controller.addSwitchContinuous(7, 3); // <-- Works
Potential causes
I am fairly novice with C++ so this I suspect I'm doing something wrong with pointers. More specifically, something seems wrong with how the Joystick_ instance gets passed around.
I have been fiddling with the constructor and trying to use references instead of pointers but I couldn't get it to work properly.
I can confirm the iteration in JFSF::loop does iterate over all actions, if I modify it with:
void JFSF::loop()
{
for (int n = 0; n < _nextActionIndex; n++)
{
if (_actions[n])
{
_actions[n]->loop();
_joystick->setButton(n, PRESSED); // Debug: Set button pressed, regardless of switch.
}
}
if (_doSendState)
{
_joystick->sendState();
}
}
then buttons 0 through n get pressed as expected. It is possible that loop() isn't properly being called, but I would expect it to fail for the N = 1 case as well in that case. Furthermore the fact the last action always succeeds would suggest the iteration is ok.
Full code
// JFSF.h
#ifndef JFSF_h
#define JFSF_h
// ... include for Arduino.h and Joystick.h; bunch of defines
namespace JFSF_PRIV
{
class AbstractAction
{
public:
virtual void loop();
};
/* A Switch that essentially acts as a push button. */
class SwitchContinuousAction : public AbstractAction
{
public:
SwitchContinuousAction(Joystick_ *joystick, int pin, int btnIndex);
void loop();
private:
Joystick_ *_joystick;
int _pin;
int _btnIndex;
};
} // namespace JFSF_PRIV
class JFSF
{
public:
JFSF(Joystick_ *joystick, bool doSendState); // doSendState should be true if Joystick_ does not auto send state.
void loop();
void addSwitchContinuous(int inputPin, int btnIndex);
private:
Joystick_ *_joystick;
JFSF_PRIV::AbstractAction *_actions[MAX_ACTIONS];
int _nextActionIndex;
bool _doSendState;
};
#endif
Source file (trimmed):
// JFSF.cpp
#include "Arduino.h"
#include "Joystick.h"
#include "JFSF.h"
#define PRESSED 1
#define RELEASED 0
// Private classes
namespace JFSF_PRIV
{
SwitchContinuousAction::SwitchContinuousAction(Joystick_ *joystick, int pin, int btnIndex)
{
_joystick = joystick;
_pin = pin;
_btnIndex = btnIndex;
pinMode(_pin, INPUT_PULLUP);
}
void SwitchContinuousAction::loop()
{
int _state = digitalRead(_pin) == LOW ? PRESSED : RELEASED;
_joystick->setButton(_btnIndex, _state);
}
} // namespace JFSF_PRIV
JFSF::JFSF(Joystick_ *joystick, bool doSendState)
{
_joystick = joystick;
_nextActionIndex = 0;
_doSendState = doSendState;
}
void JFSF::addSwitchContinuous(int inputPin, int btnIndex)
{
JFSF_PRIV::SwitchContinuousAction newBtnAction(_joystick, inputPin, btnIndex);
_actions[_nextActionIndex++] = &newBtnAction;
}
void JFSF::loop()
{
for (int n = 0; n < _nextActionIndex; n++)
{
if (_actions[n])
{
_actions[n]->loop();
}
}
if (_doSendState)
{
_joystick->sendState();
}
}
For completeness sake, this is the code for the Arduino, but it is pretty much just declarations:
#include <JFSF.h>
// ... A bunch of const declarations used below. These are pretty self explanatory.
// See: https://github.com/MHeironimus/ArduinoJoystickLibrary#joystick-library-api
Joystick_ joystick(HID_REPORT_ID,
JOYSTICK_TYPE_JOYSTICK, // _JOYSTICK, _GAMEPAD or _MULTI_AXIS
BTN_COUNT, HAT_SWITCH_COUNT,
INCLUDE_X_AXIS, INCLUDE_Y_AXIS, INCLUDE_Z_AXIS,
INCLUDE_RX_AXIS, INCLUDE_RY_AXIS, INCLUDE_RZ_AXIS,
INCLUDE_RUDDER, INCLUDE_THROTTLE,
INCLUDE_ACCELERATOR, INCLUDE_BRAKE, INCLUDE_STEERING);
JFSF controller(&joystick, !DO_AUTO_SEND_STATE);
void setup() {
joystick.begin(DO_AUTO_SEND_STATE);
controller.addSwitchContinuous(10, 0); // <-- Doesn't work
controller.addSwitchContinuous(9, 1); // <-- Works
}
void loop() {
controller.loop();
}
References
ArduinoJoystickLibrary (Source for Joystick_) can be found here: https://github.com/MHeironimus/ArduinoJoystickLibrary#joystick-library-api
I dont really understand your code. Please read How to create a Minimal, Complete and Verifiable example. Anyhow, the following is certainly wrong and likely the cause of your problem:
void JFSF::addSwitchContinuous(int inputPin, int btnIndex)
{
JFSF_PRIV::SwitchContinuousAction newBtnAction(_joystick, inputPin, btnIndex);
_actions[_nextActionIndex++] = &newBtnAction;
}
Lets rewrite it a bit for clarity:
void foo(){
T bar;
container[index] = &bar;
}
What happens here is that bar gets destroyed when it goes out of scope, hence the pointer you put into the container, points to garbage. Presumably somewhere else in your code you are dereferencing those pointers, which is undefined behaviour (aka anything can happen).
Long story short: It is a common pattern among c++ beginners to overuse pointers. Most likely you should make container a container of objects rather than pointers and make use of automatic memory managment instead of trying to fight it.
Thanks to #user463035818 and #drescherjm for identifiying the actual problem.
So in the end I fixed it by simply moving the Action object creation up to the Arduino code (where it's essentially global) and passing references to those objects to the controller.
In code this translates to:
JFSF.cpp
void JFSF::addAction(JFSF_PRIV::AbstractAction *action){
_actions[_nextActionIndex++] = action;
}
Arduino code (ino)
// See code in original post
JFSF controller(&joystick, !DO_AUTO_SEND_STATE);
JFSF_PRIV::SwitchContinuousAction btnOne(&joystick, 10, 0);
JFSF_PRIV::SwitchContinuousAction btnTwo(&joystick, 9, 1);
void setup() {
joystick.begin(DO_AUTO_SEND_STATE);
// controller.addSwitchContinuous(10, 0); // Pin 10; btn index 0
// controller.addSwitchContinuous(9, 1); // Pin 9 ; btn index 1
controller.addAction(&btnOne);
controller.addAction(&btnTwo);
}
// loop() is unchanged
its my first time here. My code is suppose to make two ultrasonic sensors function at the same time using an mbed. However, i cant seem to make both classes void us_right() and void us_left() in the code run concurrently. Help please :(
#include "mbed.h"
DigitalOut triggerRight(p9);
DigitalIn echoRight(p10);
DigitalOut triggerLeft(p13);
DigitalIn echoLeft(p14);
//DigitalOut myled(LED1); //monitor trigger
//DigitalOut myled2(LED2); //monitor echo
PwmOut steering(p21);
PwmOut velocity(p22);
int distanceRight = 0, distanceLeft = 0;
int correctionRight = 0, correctionLeft = 0;
Timer sonarRight, sonarLeft;
float vo=0;
// Velocity expects -1 (reverse) to +1 (forward)
void Velocity(float v) {
v=v+1;
if (v>=0 && v<=2) {
if (vo>=1 && v<1) { //
velocity.pulsewidth(0.0014); // this is required to
wait(0.1); //
velocity.pulsewidth(0.0015); // move into reverse
wait(0.1); //
} //
velocity.pulsewidth(v/2000+0.001);
vo=v;
}
}
// Steering expects -1 (left) to +1 (right)
void Steering(float s) {
s=s+1;
if (s>=0 && s<=2) {
steering.pulsewidth(s/2000+0.001);
}
}
void us_right() {
sonarRight.reset();
sonarRight.start();
while (echoRight==2) {};
sonarRight.stop();
correctionRight = sonarLeft.read_us();
triggerRight = 1;
sonarRight.reset();
wait_us(10.0);
triggerRight = 0;
while (echoRight==0) {};
// myled2=echoRight;
sonarRight.start();
while (echoRight==1) {};
sonarRight.stop();
distanceRight = ((sonarRight.read_us()-correctionRight)/58.0);
printf("Distance from Right is: %d cm \n\r",distanceRight);
}
void us_left() {
sonarLeft.reset();
sonarLeft.start();
while (echoLeft==2) {};
sonarLeft.stop();
correctionLeft = sonarLeft.read_us();
triggerLeft = 1;
sonarLeft.reset();
wait_us(10.0);
triggerLeft = 0;
while (echoLeft==0) {};
// myled2=echoLeft;
sonarLeft.start();
while (echoLeft==1) {};
sonarLeft.stop();
distanceLeft = (sonarLeft.read_us()-correctionLeft)/58.0;
printf("Distance from Left is: %d cm \n\r",distanceLeft);
}
int main() {
while(true) {
us_right();
us_left();
}
if (distanceLeft < 10 || distanceRight < 10) {
if (distanceLeft < distanceRight) {
for(int i=0; i>-100; i--) { // Go left
Steering(i/100.0);
wait(0.1);
}
}
if (distanceLeft > distanceRight) {
for(int i=0; i>100; i++) { // Go Right
Steering(i/100.0);
wait(0.1);
}
}
}
wait(0.2);
}
You need to use some mechanism to create new threads or processes. Your implementation is sequential, there is nothing you do that tells the code to run concurrently.
You should take a look at some threads libraries (pthreads for example, or if you have access to c++11, there are thread functionality there) or how to create new processes as well as some kind of message passing interface between these processes.
Create two threads, one for each ultrasonic sensor:
void read_left_sensor() {
while (1) {
// do the reading
wait(0.5f);
}
}
int main() {
Thread left_thread;
left_thread.start(&read_left_sensor);
Thread right_thread;
right_thread.start(&read_right_sensor);
while (1) {
// put your control code for the vehicle here
wait(0.1f);
}
}
You can use global variables to write to when reading the sensor, and read them in your main loop. The memory is shared.
Your first problem is that you have placed code outside of your infinite while(true) loop. This later code will never run. But maybe you know this.
int main() {
while(true) {
us_right();
us_left();
} // <- Loops back to the start of while()
// You Never pass this point!!!
if (distanceLeft < 10 || distanceRight < 10) {
// Do stuff etc.
}
wait(0.2);
}
But, I think you are expecting us_right() and us_left() to happen at exactly the same time. You cannot do that in a sequential environment.
Jan Jongboom is correct in suggesting you could use Threads. This allows the 'OS' to designate time for each piece of code to run. But it is still not truly parallel. Each function (classes are a different thing) will get a chance to run. One will run, and when it is finished (or during a wait) another function will get its chance to run.
As you are using an mbed, I'd suggest that your project is an MBED OS 5 project
(you select this when you start a new project). Otherwise you'll need to use an RTOS library. There is a blinky example using threads that should sum it up well. Here is more info.
Threading can be dangerous for someone without experience. So stick to a simple implementation to start with. Make sure you understand what/why/how you are doing it.
Aside: From a hardware perspective, running ultrasonic sensors in parallel is actually not ideal. They both broadcast the same frequency, and can hear each other. Triggering them at the same time, they interfere with each other.
Imagine two people shouting words in a closed room. If they take turns, it will be obvious what they are saying. If they both shout at the same time, it will be very hard!
So actually, not being able to run in parallel is probably a good thing.
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.
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)
this code is make queues for the the operating system
I used structures to implement my processes
and used arr_processes to handle all of this processes
and new_processes array to sort this processes according to its arrival time
but when i run this code on visual studio 2010
it produces this run time error
Run-Time Check Failure #2 - Stack around the variable arr_processes was corrupted!
this is the code
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int id;
int arr_time;
int serv_time;
int deadline;
} process;
void print_process(process n);
int main()
{
process arr_processes[8];
process new_processes[8];
process real_processes[3];
process ready_processes[5];
process tmp_process[1];
int length_ready;
int i,length,j;
int length_real;
arr_processes[0].id=1;
arr_processes[0].arr_time=12;
arr_processes[0].serv_time=4;
arr_processes[0].deadline=0;
arr_processes[1].id=2;
arr_processes[1].arr_time=10;
arr_processes[1].serv_time=5;
arr_processes[1].deadline=0;
arr_processes[2].id=3;
arr_processes[2].arr_time=9;
arr_processes[2].serv_time=2;
arr_processes[2].deadline=0;
arr_processes[3].id=4;
arr_processes[3].arr_time=8;
arr_processes[3].serv_time=4;
arr_processes[3].deadline=10;
arr_processes[4].id=5;
arr_processes[4].arr_time=5;
arr_processes[4].serv_time=2;
arr_processes[4].deadline=8;
arr_processes[5].id=6;
arr_processes[5].arr_time=3;
arr_processes[5].serv_time=3;
arr_processes[5].deadline=0;
arr_processes[6].id=7;
arr_processes[6].arr_time=2;
arr_processes[6].serv_time=3;
arr_processes[6].deadline=0;
arr_processes[7].id=8;
arr_processes[7].arr_time=1;
arr_processes[7].serv_time=1;
arr_processes[7].deadline=28;
length=sizeof(arr_processes)/sizeof(arr_processes[0]);
printf("\t length of the processes=%i\n\n",length);
printf("\t The Original processes \n\n");
for(i=0;i<8;i++)
print_process(arr_processes[i]);
// now we want to sort the processes according to their arrival time
for(i=0;i<8;i++)
{
new_processes[i]=arr_processes[i];
}
for(i=0;i<length;i++)
{
for(j=0;j<length-i;j++)
{
if((new_processes[j].arr_time)>(new_processes[j+1].arr_time))
{
tmp_process[0]=new_processes[j];
new_processes[j]=new_processes[j+1];
new_processes[j+1]=tmp_process[0];
}
}
}
printf("\t The New processes \n\n");
for(i=0;i<8;i++)
print_process(new_processes[i]); // the new queue
ready_processes[0]=arr_processes[0];
ready_processes[1]=arr_processes[1];
ready_processes[2]=arr_processes[2];
ready_processes[3]=arr_processes[5];
ready_processes[4]=arr_processes[6];
length_ready=sizeof(ready_processes)/sizeof(ready_processes[0]);
// now we want to design the ready queue
for(i=0;i<length_ready;i++)
{
for(j=0;j<length_ready-i;j++)
{
if((ready_processes[j].arr_time)>ready_processes[j+1].arr_time)
{
tmp_process[0]=ready_processes[j];
ready_processes[j]=ready_processes[j+1];
ready_processes[j+1]=tmp_process[0];
}
}
}
printf("\t The ready processes \n\n");
for(i=0;i<length_ready;i++)
print_process(ready_processes[i]); // the ready queue
// now we want to design the ready real queue for the shortest deadline first
// we donnot need to check for the new proesses at each instant of time
//but we need to check for the service time from now
real_processes[0]=arr_processes[3];
real_processes[1]=arr_processes[4];
real_processes[2]=arr_processes[7];
length_real=sizeof(real_processes)/sizeof(real_processes[0]);
for(i=0;i<length_real;i++)
{
for(j=0;j<length_real-i;j++)
{
if((real_processes[j].deadline)>real_processes[j+1].deadline)
{
tmp_process[0]=real_processes[j];
real_processes[j]=real_processes[j+1];
real_processes[j+1]=tmp_process[0];
}
}
}
printf("\t The real processes \n\n");
for(i=0;i<length_real;i++)
print_process(real_processes[i]); // the ready real queue
// removed real process
process removed_real;
removed_real.id=0;
removed_real.arr_time=0;
removed_real.serv_time=0;
removed_real.deadline=0;
process running_process;
running_process.id=0;
running_process.arr_time=0;
running_process.serv_time=0;
running_process.deadline=0;
int counter=0;
int start_time;
while(counter<=28)
{
printf("when time = %i\n\n",counter);
// printf("\t The real processes when the counter=%i \n\n",counter);
// for(i=0;i<length_real;i++)
// print_process(real_processes[i]); // the ready real queue
// first we must check for the real processes
for(i=0;i<length_real;i++)
{
if((counter==real_processes[i].arr_time)
&&((real_processes[i].deadline)-counter)>=(real_processes[i].serv_time))
{
running_process=real_processes[i];
printf("The non zero deadline process is:%i\n",running_process.id);
real_processes[i]=removed_real;
start_time=counter; // real process
while(counter!=(start_time+running_process.serv_time))
{
printf("At time = %i,The Running Process is...\n",counter);
print_process(running_process);
counter++;
}
}
}
counter++;
}
return 0;
}
void print_process(process n)
{
if(n.deadline!=0)
printf("ID=%i\narr_time=%i\nserv_time=%i\ndeadline=%i\n\n\n",n.id,n.arr_time,n.serv_time,n.deadline);
else if(n.deadline==0)
printf("ID=%i\narr_time=%i\nserv_time=%i\n\n\n",n.id,n.arr_time,n.serv_time);
}
As you run out of index, here is a sort example:
for(i=0; i<length - 1; i++)
{
for(j=i + 1;j<length;j++)
{
if((new_processes[j].arr_time)>(new_processes[i].arr_time))
{
tmp_process[0]=new_processes[j];
new_processes[j]=new_processes[i] ;
new_processes[i]=tmp_process[0] ;
}
}
}
Or, you can use standard function:
void qsort(void *base, size_t nmemb, size_t size,
int (*compar)(const void *, const void *));
Define a comparison function:
int compare_by_arr_time(const void* a, const void* b)
{
int a_int = ((const process*)a)->arr_time;
int b_int = ((const process*)b)->arr_time;
return a_int - b_int; // or b_int - a_int
}
And use it as follows:
qsort(new_processes,
sizeof(new_processes)/sizeof(new_processes[0]),
sizeof(new_processes[0]),
compare_by_arr_time);
You get these kinds of errors when you go out of the bounds of an array.
for(i=0;i<length;i++)
{
for(j=0;j<length-i;j++)
{
if((new_processes[j].arr_time)>(new_processes[j+1].arr_time))
{
tmp_process[0]=new_processes[j];
new_processes[j]=new_processes[j+1] ;
new_processes[j+1]=tmp_process[0] ;
}
}
}
In the first iteration, i = 0, j = 0 and j must be less than 8 - i, which is 8.
Notice the expression j+1. This expression will return values in the range of [1 ... 9] during the first iteration of the outer-most loop, and thus, you will be going out of the bounds your new_processes array.
There's your problem.
edit: This problem may also be present in the for loops that follow the first one.