I have no idea why the first codeblock is working and the second is not:
For both blocks there is:
struct Object
{
vector <string> line;
};
Object myObject;
string a = "*Nset, nset=_PickedSet2, internal, generate";
myObject.line.push_back(a);
int iPos = 0;
int iPos2 = 7;
string sRefString = ","; // So I want to find the ",".
iPos = myObject.line.at(0).find_first_of(sRefString, iPos2); //Here is the issue.
So this works just fine:
cout <<"Output: "<< myObject.line.at(0).find_first_of(sRefString, iPos2);
It gives:
Output: 23
But this does not:
iPos = myObject.line.at(0).find_first_of(sRefString, iPos2);
Here i get an error:
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
zweiterminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::substr
Thanks for help!
Related
So the question explains the problem...
Background:
I'm trying to solve this problem from HackerRank.
It's basically an html tag parser. Valid input guaranteed, attributes are strings only.
My Approach
I created a custom Tag class that can store a map<string,Tag> of other Tag's, as well as a map<string,string> of attributes. The parsing seems to be working correctly.
The Problem
During the querying part, I get a BAD_ACCESS error on the following query/html combo:
4 1
<a value = "GoodVal">
<b value = "BadVal" size = "10">
</b>
</a>
a.b~size
The error occurs when I try to access the b Tag from a. Specifically, it's in the t=t.tags[tag_name], Line 118 below.
Code
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <map>
#include <stack>
using namespace std;
class Tag {
public:
Tag(){};
Tag(string name):name(name){};
string name;
map<string,Tag> tags = map<string, Tag>();
map<string,string> attribs=map<string,string>();
};
int main() {
int lines, queries;
std::cin>>lines>>queries;
std:string str;
getline(cin, str);
stack<string> open;
auto tags = map<string, Tag>();
for (int i = 0; i < lines; i++) {
getline(cin, str);
if (str.length()>1){
// If it's not </tag>, then it's an opening tag
if (str[1] != '/') {
// Parse tag name
auto wordidx = str.find(" ");
if (wordidx == -1) {
wordidx = str.length()-1.f;
}
string name = str.substr(1,wordidx-1);
auto t = Tag(name);
string sub = str.substr(wordidx);
auto equalidx=sub.find("=");
// Parse Attributes
while (equalidx != std::string::npos) {
string key = sub.substr(1,equalidx-2);
sub = sub.substr(equalidx);
auto attrib_start = sub.find("\"");
sub = sub.substr(attrib_start+1);
auto attrib_end = sub.find("\"");
string val = sub.substr(0, attrib_end);
sub = sub.substr(attrib_end+1);
t.attribs[key] = val;
equalidx=sub.find("=");
}
// If we're in a tag, push to that, else push to the base tags
if (open.size() == 0) {
tags[name] = t;
} else {
tags[open.top()].tags[name]=t;
}
open.push(name);
} else {
// Pop the stack if we reached a closing tag
auto wordidx = str.find(">");
string name = str.substr(2,wordidx-2);
// Sanity check, but we're assuming valid input
if (name.compare(open.top())) {
cout<<"FUCK"<<name<<open.top()<<endl;
return 9;
}
open.pop();
}
} else {
std::cout<<"FUCK\n";
}
}
//
// Parse in queries
//
for (int i = 0; i < queries; i++) {
getline(cin, str);
Tag t = Tag();
bool defined = false;
auto next_dot = str.find(".");
while (next_dot!=string::npos) {
string name = str.substr(0,next_dot);
if (defined && t.tags.find(name) == t.tags.end()) {
//TAG NOT IN T
cout<<"Not Found!"<<endl;
continue;
}
t = !defined ? tags[name] : t.tags[name];
defined = true;
str = str.substr(next_dot+1);
next_dot = str.find(".");
}
auto splitter = str.find("~");
string tag_name = str.substr(0,splitter);
string attrib_name = str.substr(splitter+1);
if (!defined) {
t = tags[tag_name];
} else if (t.tags.find(tag_name) == t.tags.end()) {
//TAG NOT IN T
cout<<"Not Found!"<<endl;
continue;
} else {
t = t.tags[tag_name];
}
// T is now set, check the attribute
if (t.attribs.find(attrib_name) == t.attribs.end()) {
cout<<"Not Found!"<<endl;
} else {
cout<<t.attribs[attrib_name]<<endl;
}
}
return 0;
}
What I've tried
This is fixed by just defining Tag x = t.tags[tag_name]; in the line above as a new variable, and then doing t = x; but why is this even happening?
Also, the following query also then fails: a.b.c~height, but it fails on Line 99 when it tried to get a.tags["b"]. No idea why. I was gonna just go with the hacky fix above, but this seems like a big core issue that i'm doing wrong.
I would suggest running this on an IDE and verifying that the parsing is indeed correct.
t=t.tags[tag_name]
This expression is unsafe because you are copy-assigning an object that is owned by that object over the owning object.
Consider what happens on this line:
The map lookup is performed and returns a Tag&.
You try to copy-assign this to t, invoking the implicit copy-assigment operator.
This operator copy-assigns t.tags from the tags attribute of the copy source -- which lives in t.tags.
The result is that the object you're copying into t is destroyed in the middle of that copy. This causes undefined behavior, and an immediate crash is honestly the best possible outcome as it told you exactly where the problem was. (This kind of problem frequently manifests at some point later in the program, at which point you've lost the state necessary to figure out what caused the UB.)
One workaround would be to move the source object into a temporary and then move-assign that temporary over t:
t = Tag{std::move(t.tags[tag_name])};
This lifts the data we want to assign to t out of t before we try to put it in t. Then, when t's assignment operator goes to replace t.tags, the data you're trying to assign to t doesn't live there anymore.
However, this overall approach involves a lot of unnecessary copying. It would be better to declare t as Tag const *t; instead -- have it be a pointer to a tag. Then you can just move that pointer around to point at other tags in your data structure without making copies.
Side note: I just did this problem the other day! Here's a hint that might help you simplify things: do you actually need a structure of tags? Is there a simpler type of lookup structure that would work instead of nested tags?
I am trying to use the bsoncxx library to access records from mongdb using C++. however when i try to retrieve the element type as shown in the code below i get the error shown below. Ive been going round in circles trying to figure this out, but i feel stumped.
My error msg:
terminate called after throwing an instance of 'bsoncxx::v_noabi::exception'
what(): unset document::element.
My Code:
using namespace bsoncxx;
int main(int, char**) {
//const std::uint8_t* recdata;
//const std::uint8_t* elbytes[100000];
mongocxx::instance inst{};
mongocxx::client conn{mongocxx::uri{}};
auto collection = conn["simpleemdb"]["priceCurves"];
auto cursor = collection.find({});
int counter =0;
for (auto&& doc : cursor) {
//recdata=doc.data();
if (counter ==0){
auto cEle= doc["curve_name"];
type eltype= cEle.type();
}
counter++;
}
}
can anyone help me understand why this is happening
I was trying to build up on the example sumo client server in c++ as in the link
http://sumo.dlr.de/wiki/TraCI/C%2B%2BTraCIAPI
I wrote a function to build a complete RedYellowGreenDef as in the function below:
std::vector<libsumo::TraCILogic> Client::buildCompletetrafficLogics(std::string tlID, int phaseIndex, int increaseVal)
{
std::vector<libsumo::TraCILogic> logics = trafficlights.getCompleteRedYellowGreenDefinition(tlID);
for (int i = 0; i < (int)logics.size(); ++i)
{
for (int j = 0; j < (int)logics[i].phases.size(); ++j)
{
if (logics[i].currentPhaseIndex = phaseIndex)
{
logics[i].phases[j].duration = logics[i].phases[j].duration + increaseVal; //increase duration by 5 seconds
logics[i].phases[j].duration2 = logics[i].phases[j].duration2+ increaseVal;
}
}
}
return logics;
}
I called this function in the main function as follows:
//increase duration of phase with index "PhaseIndex" by 5000ms
std::vector<libsumo::TraCILogic> logics = client.buildCompletetrafficLogics(*tlIt, phaseIndex,5000);
libsumo::TraCILogic logic = logics[0];
client.trafficlights.setCompleteRedYellowGreenDefinition(tlID, logic);
where tlID is a valid traffic light id, but I faced The following exception when I passed the built logic to setCompleteRedYellowGreenDefinition():
terminate called after throwing an instance of 'std::invalid_argument'
what(): Storage::writeUnsignedByte(): Invalid value, not in [0, 255]
Aborted (core dumped)
Could you help me to find the problem: why I got this exception and how to tackle it?
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)
Need Help.
I am doing work on facial emotion recognition in VS2010 using OPENCV and FANN Library. It Build successfully but running it give following error:
Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
at fann_run(fann* , Single* )
at main() in c:\down\uf-lightbot-read-only\src\emo_test.cpp:line 24
at mainCRTStartup()
Code is as follows:
#include <iostream>
#include "fann.h"
using namespace std;
int main()
{
fann_type *calc_out;
fann_type input[10];
struct fann *ann = fann_create_from_file("emotions.net");
input[0] = 0.87;
input[1] = 1.20;
input[2] = 1.03;
input[3] = 1.45;
input[4] = 0.96;
input[5] = 1.00;
input[6] = 0.98;
input[7] = 1.486;
input[8] = 1.042;
input[9] = 1.016;
calc_out = fann_run(ann, input);
cout<<calc_out[0]<<" "<<calc_out[1]<<" "<<calc_out[2]<<" "<<calc_out[3]<<endl;
fann_destroy(ann);
return 0;
}
Can any body help me what is the problem ?
Waiting for guidance. . .
Thanks.
Problem solved. Emotion.net contain doesn't contain some of required variables.