Vector in c++ error when trying to call at() - c++

I'm trying to get a pointer to mytype of a vector(vector mytype*) but I get segmegation fault.
I've the following code:
void add(string b, vector<mytype*> *p){
int a;
mytype *fre=NULL;
a=oura.front();
oura.pop();
if(!(p->size()<a) && oura.size()>0){
fre=p->at(a-1); //Error seems to come from here
add(b,fre->get_vec());
}
else{ ...}
}
mytype was a class with a string and a vector<mytype*> pointer.
The error seems to come from fre=p->at(a-1)
oura is a queue<int> and takes values between 1-20 so i used (a-1).

at does bounds checking when accessing elements. If it's out of bounds it will throw an std::out_of_range exception.
adding an assert(a > 0); should let you find out when it happens.

Related

Why is my out_of_range exception not being caught

I am new to cpp and I am trying out several things. This one I can't seem to figure out on my own.
#include <cstdio>
#include <stdexcept>
template <class E, class V>
struct Pair {
E first;
V second;
Pair(E fst, V snd) : first(fst), second(snd) {}
E getFirst() { return first; }
V getSecond() { return second; }
};
template <class t, unsigned dim>
struct vec {
t d[dim];
static constexpr int dimen = dim;
t &operator[](unsigned n) {
std::printf("dim: %d %d\n", dim, n);
if (n >= dim) {
std::printf("checking %d\n", n);
throw std::out_of_range("vector index is out of range");
}
return d[n];
};
};
int main() {
try {
Pair<int, vec<int, 2> *> test2(2, new vec<int, 2>{1, 2});
std::printf("%d\n", test2.getSecond()->dimen);
std::printf("before\n");
std::printf("%d\n", test2.getSecond()->d[2]); // it seems like the compiler kind of ignores this
} catch (std::out_of_range e) {
std::printf("Caught!!");
}
return 0;
}
Now, the line std::printf("%d\n", test2.getSecond()->d[2]); should ideally throw the out_of_range error, but it is not. My linter actually warns me that this is out of range also. I can compile and run the program and it returns some garbage 0 value.
My question is: why is either the error not being thrown or the error not being caught? I think the error is not being thrown because checking is not printed when I run it.
Because the throw code is never actually reached.
In this line here:
std::printf("%d\n", test2.getSecond()->d[2]);
getSection() returns a pointer to the vec object. When you then do ->d you are accessing the d array, within the vec object. Thus, when you add the [2] to the end, you are accessing the element at index 2 of the array, and are not calling operator[] of the vec object.
If you rewrite like this:
std::printf("%d\n", (*test2.getSecond())[2]);
Then the operator[] will be called on the vec object, and not its array. Note that you have to dereference the result of getSecond(). Alternatively, you can be more verbose:
std::printf("%d\n", test2.getSecond()->operator[](2));
Working example: https://godbolt.org/z/YWKzPz
Very good question!
The issue is that when you try to reference an item in an array via index, such as [2], you are actually referring to the size * 2 location. There is no built-in protection against it, but you can always check for \0 as that's where your arrays end. When you use arrays in C/C++, it is your job to make sure you are not outside of their location. It's generally a good idea to keep your array inside your structure/class and allow reaching its elements with setters and getters, which would handle the bounds and throw exceptions if those are violated.

priority_queue Invalid Heap - Debug Assertation Fault

I'm experiencing huge problem with priority_queue STL container.
I'm using it to sort objects by parameter x.
Code used to compare by objects parameter.
class CompareX {
public:
bool operator() (MyClass *e1, MyClass *e2) {
return e1->get_x() > e2->get_x();
}
};
Definition of priority_queue in main:
priority_queue<MyClass*, vector<MyClass*>, CompareX > my_queue;
Sorting works fine, but here's code where I get Debug Assertation Fault - Invalid Heap:
if(condidion == false)
{
double n = 200;
my_queue.top()->modifyX(clock, n); //Here I modify parameter X (it becomes bigger)
my_queue.push(my_queue.top());
my_queue.pop();
}
My goal is to modify parameter X to a bigger one, and re insert object into my_queue to sort it again. What's wrong?

Invalid deque <T> subscript . Why am I getting this error?

I am getting the execption error in the following piece of code. Any suggestions on what might be causing it ?
Error : Invalid deque <T> subscript
typedef boost::shared_ptr<HistObj> shared_hist_def;
typedef std::deque<shared_hist_def> vector_def;
typedef boost::shared_ptr<vector_def> shared_vector_def;
typedef boost::unordered_map<int,shared_vector_def> in_map_def;
typedef boost::shared_ptr<in_map_def> shared_inner_map_def;
Domain::shared_hist_def& Domain::GetSpecificHistoricalTuple(const std::string& symb,const int& tframe,const int& val)
{
Domain::shared_inner_map_def tshare = stat_History_base[symb];
shared_vector_def tmp = tshare->at(tframe);
try
{
Domain::shared_hist_def safe_tuple = tmp->at(val);
return safe_tuple;
}
catch (std::exception &ex)
{
std::string a = ex.what();
__debugbreak();
}
}
More information:
The above method is a static method. And the program is multithreaded.Any chance that this error occurs because multiple threads access it. I had that assumption but then think that function parameters above could never be the same at one time.
Your val parameter seems to be too high (greater or equal to the number of elements in the deque), or maybe it's negative.

Passing a specific array element using pointer reference

I am having problem with passing a pointer by reference.
This is the method
void set_range(double **measu)
{
if ((*measu)[0] < 0) //or i is used for a loop
return ;
}
int main()
{
double *mes;
set_range(&mes[1]);
}
I have allocated memory and required values are set. But this program gives me "Unhandled exception Access violation reading location" error.
So my question is,how to pass the pointer of mes[1] instead of mes[0] (which normally passed when (&mes) is given) to the set_range method?
One problem is that &mes[1] is of type double *, not the double ** required of your function.
Another problem is that mes doesn't point to anything - it's uninitialized. So dereferencing it will access junk (which is why you get an access violation).
I'm trying to come up with some code to help clarify, but honestly I have no idea what you're trying to do. Some more code would help us figure out what your goal is, but just given the above I have no idea why you need a double ** or whether you need dynamic memory or just a single double variable.
Change your function to take a double* instead of a double**, eg:
void set_range(double *measu)
{
if (*measu < 0) //or i is used for a loop
return;
}
int main()
{
double *mes;
...
set_range(&mes[1]);
}
Alternatively, use a real reference instead:
void set_range(double &measu)
{
if (measu < 0) //or i is used for a loop
return;
}
int main()
{
double *mes;
...
set_range(mes[1]);
}

was not declared in this scope C++

Why do I get this error in the code below?
class ST : public Instruction{
public:
ST (string _name, int _value):Instruction(_name,_value){}
void execute(int[]& anArr, int aVal){
//not implemented yet
cout << "im an st" <<endl;
anArr[value] = aVal;
}
virtual Instruction* Clone(){
return new ST(*this);
}
};
classes.h:81: error: ‘anArr’ was not declared in this scope
classes.h:81: error: ‘aVal’ was not declared in this scope
You have a problem with the type of the first parameter of your execute function. Read this up to know more about how to pass arrays around.
Because the type of anArr is invalid.
Also you may be interested in using a covariant return type on your clone method. I.e. it can return a pointer to ST instead of Instruction.
Try this out :
void execute(int anArr[] , int aVal)
since You cant use array of reference .
If execute() is supposed to be taking an array of integers, you should probably declare it like this:
void execute(int* anArr, int anArrLength, int aVal)
{
// ...
}
Note that there are several differences to your method:
anArr is passed in as a pointer to the start of the array. The client code can simply pass in the array variable name, as by definition this is equivalent to "a pointer to the start of the array".
anArrLength is passed in to indicate the length of the array. This is required to ensure that the execute() method doesn't access memory which is out of the bounds of the array (or what has been allocated for the array). Doing so could result in memory corruption.
You could improve the method signature above by adding a return value to indicate success or failure. This would allow the client code to detect if there have been any problems. For example:
// Returns true on success, false on failure
bool execute(int* anArr, int anArrLength, int aVal)
{
// Get "value" through whatever means necessary
// ...
if (value >= anArrLength)
{
// Out of bounds of array!
return false;
}
anArr[value] = aVal;
// Do whatever else you need to do
// ...
return true;
}