Program crashes without error message - c++

I am using the Qt Creator (Community) to learn how to code.
I have an assignment to calculate the roots of a function, and I tried using the code I found here in a Qt Widgets Project.
When I try to run the program, Qt didn't detect any errors.
However, my program crashes whenever I try to show the results using on_pushButton_clicked().
My lecturer suspects there should be an open loop somewhere but I don't see any.
Any help would be very much appreciated.
Code below:
double function1(double q)
{
double ab = ((q*q*q)+(9*q*q)-(15*q)+98)*(sin(q));
return ab;
}
void MainWindow::on_pushButton_clicked()
{
ui->label->setText(tr("%1").arg(func1()));
}
double MainWindow::func1()
{
std::setprecision(4);
double precision = 0.001;
double a = -10;
double b = -9;
double product = function1(a)*function1(b);
double absolute = fabs(a-b);
double e = 0;
if (product>0)
{
++a;
++b;
}
else
{
while (absolute >= precision)
{
e = (a + b) / 2;
double fa = function1(a);
double fe = function1(e);
if (fe == 0)
{
return e;
break;
}
if (fa*fe>0)
{
a = e;
}
else if (fa*fe<0)
{
b = e;
}
}
}
return e;
}

Try printing out the values of absolute and precision everytime this loop happens:
while (absolute >= precision)
.
That should help you figure it out.

If the program crashes when you click the button that "calls" on_pushButton_clicked, then it something wrong inside this slot.
Firstly, are all heap memory objects created previously with a new statement (in particular label)?
PS: you can remove the break instruction, function has already exited the while loop due to return in the line before.

Related

How to use std::any_of inside a class with lambda expression?

I'm coding a small simulation in c++ with robots and I need to check if the robot are colliding. I implemented this function in my simulation's class:
bool World::isRobotColliding(Robot *r) {
for (Robot *other_robot: robots) {
double d = distance(r->getX(), r->getY(), other_robot->getX(), other_robot->getY());
if ((r->getRadius() + other_robot->getRadius()) >= d) return true;
}
return false;
}
double World::distance(const double &x_1, const double &y_1, const double &x_2, const double &y_2) const {
return sqrt((x_1 - x_2) * (x_1 - x_2) + (y_1 - y_2) * (y_1 - y_2));
}
Here my IDE suggested me to replace the for loop with the std::any_of() method. However, I was unable to use it properly. This is what I tried:
return std::any_of(robots.begin(), robots.end(), [r, this](const Robot *&other_robot) {
return
(r->getRadius() + other_robot->getRadius())
>=
distance(r->getX(), r->getY(), other_robot->getX(), other_robot->getY());
});
How can I use std::any_of() in my context?
Thank you
Thank you everyone for your advise,
The issue was the pointer passed by reference.
return std::any_of(robots.begin(), robots.end(), [r, this](const Robot *other_robot) {
double d = distance(r->getX(), r->getY(), other_robot->getX(), other_robot->getY());
if(d == 0) return false;
return
(r->getRadius() + other_robot->getRadius())
>=
d;
});
This snippet do exactly what I was expecting.
I needed to pass the first robot r in the context as well as this. I could have declared a distance function in my robot and ommiting the this.

g++ optimization makes the program unable to run

I implemented a path planning algorithm based on D*-Lite. When I do not turn on optimization (-O0), the program can run normally. But when I turn on the optimization level (-O1/2/3), the program cannot be terminated. In Visual Studio, both debug mode and release mode can run normally. In the above cases, the codes are the same.I don’t know how to find the problem, can anyone help me?
class DstarLite {
public:
DstarLite() = delete;
DstarLite(GridStatus* a, GridStatus* b, FILE* fp)
: k_m_(0), start_(a), last_(start_), goal_(b), open_close_(fp) {}
void calculateKey(GridStatus* s);
void updateVertex(GridStatus* u);
void initialize();
void computeShortestPath();
void rePlanning(vector<pair<GridStatus*, int>>& node_change);
GridStatus* getStart();
void setStart(GridStatus* val);
GridStatus* getGoal();
private:
Fib frontier_;
double k_m_;
unordered_map<GridStatus*, handle_t>
heap_map_;
GridStatus* start_;
GridStatus* last_;
GridStatus* goal_;
FILE* open_close_;
};
void DstarLite::calculateKey(GridStatus* s) {
s->f = min(s->g, s->rhs) + heuristic(start_, s) + k_m_;
s->k2 = min(s->g, s->rhs);
}
void DstarLite::initialize() {
fprintf(open_close_, "%d %d\n", start_->x, start_->y);
fprintf(open_close_, "%d %d\n", goal_->x, goal_->y);
goal_->rhs = 0;
calculateKey(goal_);
handle_t hand = frontier_.push(goal_);
heap_map_[goal_] = hand;
}
void DstarLite::updateVertex(GridStatus* u) {
bool heap_in = heap_map_.find(u) != heap_map_.end();
if (u->g != u->rhs && heap_in) {
calculateKey(u);
frontier_.update(heap_map_[u]);
} else if (u->g != u->rhs && !heap_in) {
calculateKey(u);
handle_t hand = frontier_.push(u);
heap_map_[u] = hand;
} else if (u->g == u->rhs && heap_in) {
calculateKey(u);
frontier_.erase(heap_map_[u]);
heap_map_.erase(u);
}
}
void DstarLite::computeShortestPath() {
int count = 0;
while (smaller(frontier_.top(), start_) || !myEqual(start_->rhs, start_->g)) {
count++;
auto u = frontier_.top();
pair<double, double> k_old = {u->f, u->k2};
pair<double, double> k_new;
k_new.first = min(u->g, u->rhs) + heuristic(start_, u) + k_m_;
k_new.second = min(u->g, u->rhs);
if (k_old < k_new) {
calculateKey(u);
frontier_.update(heap_map_[u]);
} else if (myGreater(u->g, u->rhs)) {
u->g = u->rhs;
frontier_.pop();
heap_map_.erase(u);
for (auto s : neighbors(u)) {
if (s->rhs > u->g + cost(u, s)) {
s->next = u;
s->rhs = u->g + cost(u, s);
updateVertex(s);
}
}
} else {
double g_old = u->g;
u->g = kDoubleInfinity;
auto neighbor = neighbors(u);
neighbor.push_back(u);
for (auto s : neighbor) {
if (myEqual(s->rhs, cost(s, u) + g_old)) {
if (!equal(s, goal_)) {
double pp_s = kDoubleInfinity;
for (auto succ : neighbors(s)) {
double dis = succ->g + cost(succ, s);
if (dis < pp_s) {
pp_s = dis;
s->next = succ;
}
}
s->rhs = pp_s;
}
}
updateVertex(s);
}
}
}
cout << "Dstar visited nodes : " << count << endl;
}
void DstarLite::rePlanning(vector<pair<GridStatus*, int>>& node_change) {
k_m_ += heuristic(last_, start_);
last_ = start_;
for (auto change : node_change) {
GridStatus* u = change.first;
int old_threat = u->threat;
int new_threat = change.second;
double c_old;
double c_new;
u->threat = new_threat;
u->rhs += (new_threat - old_threat) * threat_factor;
updateVertex(u);
for (auto v : neighbors(u)) {
u->threat = old_threat;
c_old = cost(v, u);
u->threat = new_threat;
c_new = cost(v, u);
if (c_old > c_new) {
if (v != goal_) {
if (v->rhs > u->g + c_new) {
v->next = u;
v->rhs = u->g + c_new;
}
}
} else if (myEqual(v->rhs, c_old + u->g)) {
if (v != goal_) {
double pp_s = kDoubleInfinity;
for (auto pre : neighbors(v)) {
double dis = pre->g + cost(pre, v);
if (dis < pp_s) {
pp_s = dis;
v->next = pre;
}
}
v->rhs = pp_s;
}
}
updateVertex(v);
}
}
}
GridStatus* DstarLite::getStart() { return start_; }
void DstarLite::setStart(GridStatus* val) { start_ = val; }
GridStatus* DstarLite::getGoal() { return goal_; }
DstarLite dstar(start, goal, open_close);
dstar.initialize();
dstar.computeShortestPath();
Sorry, I think it is difficult to locate the problem in the code, so the code was not shown before. Now I have re-edited the question, but there are a lot of codes, and the main calling part is computeShortest().
As you did not provide any code, we can give you only some general hints to fix such problems.
As a first assumption your code has definitely one or more bugs which causes what we call undefined behaviour UB. As the result is undefined, it can be anything and is often changing behaviour with different optimization levels, compiler versions or platforms.
What you can do:
enable really ALL warnings and fix them all! Look especially for something like "comparison is always...", "use of xxx (sometimes) without initialization", " invalid pointer cast", ...
try to compile on different compilers. You should also try to use gcc and/or clang, even on windows. It is maybe hard in the first time to get the environment for these compilers run on windows plattforms, but it is really worth to do it. Different compilers will give different warnings. Fixing all warnings from all compilers is a really good help!
you should use memory tracers like valgrind. I have not much experience on windows, but I believe there are also such tools, maybe already integrated in your development suite. These tools are really good in finding "of by x" access, access freed memory and such problems.
if you still run into such trouble, static code analyser tools may help. Typically not as much as managers believe, because today's compilers are much better by detecting flaws as expected by dinosaur programmers. The additional findings are often false positives, especially if you use modern C++. Typically you can save the money and take a class for your own education!
Review, Review, Review with other people!
snip the problem small! You should spend most of your development time by setting up good automated unit tests. Check every path, every function in every file. It is good to see at minimum 95% of all branches covered by tests. Typically these tests will also fail if you have UB in your code if you change optimizer levels and or compiler and platforms.
using a debugger can be frustrating. In high optimized code you jump through all and nothing and you may not really see where you are and what is the relation to your code. And if in lower optimizer level the bug is not present, you have not really much chance to see find the underlying problem.
last but not least: "printf debugging". But this may change the behaviour also. In worst case the code will run always if you add a debug output. But it is a chance!
use thread and memory sanitizers from your compiler.
The problem is caused by the comparison of floating-point numbers. I deliberately put aside this question when I wrote the code before :). Now it can operate normally after being fixed.

Different behavior while debugging than while running

I have problem with running and debugging my program.
The thing is that when I run my program by 'Run' there is some bug, but when I'm trying to debug it, then it works fine.
I don't have a clue how to solve that.
There is link for short video: Video presenting problem
While running 2 sectors don't work, while debugging everything works fine.
I'm using CLion.
I find that different behavior happens in this function(it's only a piece of code, because whole project is quite big):
LevelSegmentCords* Space::findPlaceForBruteForce(int x, int y, int z) {
LevelSegmentCords *segmentCords = nullptr;
int i;
for(i=0;i<this->getHeight();i++){
int lastX=0,lastY=0;
int checkerX=0,checkerY=0;
do{
segmentCords = levels[i].findFreeSector(x,y,lastX,lastY);
if(segmentCords != nullptr){
segmentCords->setStartLevel(i);
for(int j=0;i+j<this->getHeight() && j<=z;j++){
if(!levels[i+j].isSectorFree(segmentCords->getX1(),
segmentCords->getY1(),
segmentCords->getX2()+1,
segmentCords->getY2()+1)){
checkerX = segmentCords->getX1();
checkerY = segmentCords->getY1();
}
}
if(checkerX != lastX || checkerY != lastY){
if(checkerX + 1 < this->x){
lastX = checkerX+1;
lastY = checkerY;
}else{
break;
}
}else{
return segmentCords;
}
}else{
break;
}
}while(true);
}
return nullptr;
}
This function should basically find place to put there cuboid.

terminate called after throwing an instance of std::bad_alloc

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)

NLOpt with windows forms

I am suffering serious problems while trying to use nlopt library (http://ab-initio.mit.edu/wiki/index.php/NLopt_Tutorial) in windows forms application. I have created following namespace which runs perfectly in console application.
#include "math.h"
#include "nlopt.h"
namespace test
{
typedef struct {
double a, b;
} my_constraint_data;
double myfunc(unsigned n, const double *x, double *grad, void *my_func_data)
{
if (grad) {
grad[0] = 0.0;
grad[1] = 0.5 / sqrt(x[1]);
}
return sqrt(x[1]);
}
double myconstraint(unsigned n, const double *x, double *grad, void *data)
{
my_constraint_data *d = (my_constraint_data *) data;
double a = d->a, b = d->b;
if (grad) {
grad[0] = 3 * a * (a*x[0] + b) * (a*x[0] + b);
grad[1] = -1.0;
}
return ((a*x[0] + b) * (a*x[0] + b) * (a*x[0] + b) - x[1]);
}
int comp()
{
double lb[2] = { -HUGE_VAL, 0 }; /* lower bounds */
nlopt_opt opt;
opt = nlopt_create(NLOPT_LD_MMA, 2); /* algorithm and dimensionality */
nlopt_set_lower_bounds(opt, lb);
nlopt_set_min_objective(opt, myfunc, NULL);
my_constraint_data data[2] = { {2,0}, {-1,1} };
nlopt_add_inequality_constraint(opt, myconstraint, &data[0], 1e-8);
nlopt_add_inequality_constraint(opt, myconstraint, &data[1], 1e-8);
nlopt_set_xtol_rel(opt, 1e-4);
double x[2] = { 1.234, 5.678 }; /* some initial guess */
double minf; /* the minimum objective value, upon return */
int a=nlopt_optimize(opt, x, &minf) ;
return 1;
}
}
It optimizes simple nonlinear constrained minimization problem. The problem arises when I try to use this namespace in windows form application. I am constantly getting unhandled exception in myfunc which sees "x" as empty pointer for some reason and therefore causes error when trying to access its location. I believe that the problem is somehow caused by the fact that windows forms uses CLR but I dont know if it is solvable or not. I am using visual studio 2008 and the test programs are simple console project (which works fine) and windows forms project (that causes aforementioned errors).
My test code is based on tutorial for C from the provided link. I although tried C++ version which once again works fine in console application but gives debug assertion failed error in windows forms application.
So I guess my questions is : I have working windows forms application and I would like to use NLOpt. Is there a way to make this work ?