I was solving a question on leet in which I tried to recursion with stacks.
But during the execution
runtime error: reference binding to misaligned address 0xbebebebebebec0ba for type 'int', which requires 4 byte alignment (stl_deque.h) 0xbebebebebebec0ba: note: pointer points here <memory cannot be printed> SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_deque.h:180:16
I dont understand that it is because of the recursion or something about a memory problem.
https://leetcode.com/problems/daily-temperatures/description/
this was the question.
class Solution
{
public:
vector<int> dailyTemperatures(vector<int> &temp)
{
vector<int> dp;
for (int i = temp.size() - 1; i >= 0; i--)
{
check(i, temp, dp);
}
return dp;
}
void check(int i, vector<int> &temp, vector<int> &dp)
{
stack<int> st;
if (temp[i] > temp[st.top()])
{
if (st.empty())
{
dp[i] = 0;
}
else
{
st.pop();
check(i, temp, dp);
}
}
else
{
dp[i] = st.top() - i;
st.push(i);
}
}
};
It's a memory problem. You have undefined behaviour right here
stack<int> st;
if (temp[i] > temp[st.top()])
Stack st is empty but you are trying to retrieve the top element.
Not sure what the solution is as all paths though your code seem to try to access the top element of the stack.
There is also a problem with vector dp, it is empty, it never gets any elements added to it, but you try to assign to it with dp[i] = in a couple of places. So that's another memory problem.
Related
I'm trying to implement an alternative to usual contiguous dynamic arrays, where I am using a vector of pointers, each is pointing to a constant size array, referring to it as XVector.
It works fine for a certain limit of inputs - say 150 elements -, but beyond that it starts throwing exceptions.
I tried to use "new and delete" instead of "malloc and free", it did increased the limit - say about 1200 elements -, but still exists the same problem.
I'm using C++.
Here's my main program:
XVector<int> xv;
for(int i=0;i<1210;i++){
int temp = rand()%100;
xv.pushBack(temp);
}
for(int i=0;i<xv.size();i++){
cout<<xv.getValue(i)<<" ";
}
cout<<"\n\n"<<xv.capacity();
return 0;
And here's is the XVector (The class of theD header file:
private:
const int b = 10;
vector<T*> arr;
int currentIndex;
int maxSize;
protected:
void expand(){
T* temp = new T[b];
arr.push_back(temp);
maxSize+=(b);
}
void shrink(){
delete[] arr[arr.size()-1];
arr[arr.size()-1] = NULL;
arr.pop_back();
maxSize-=(b);
}
int ceil(float num) {
int inum = (int)num;
if (num == (float)inum) {
return inum;
}
return inum + 1;
}
pair<int,int> position(int index){
pair<int,int> pos;
float result = ((float)index/b);
pos.first = result; //Row #
pos.second = ceil((result - pos.first)*b); //Exact cell in the row
return pos;
}
public:
XVector(){
currentIndex=0;
maxSize=b;
arr.reserve(120);
arr.push_back(new T[b]);
}
void pushBack(T value){
if(currentIndex>=maxSize-1){expand();}
pair<int,int> indeces = position(currentIndex);
arr[indeces.first][indeces.second]=value;
currentIndex++;
}
void popBack(){
currentIndex--;
if(maxSize>=currentIndex+(2*b)){shrink();}
}
T getValue(int index){
pair<int,int> indeces = position(index);
return arr[indeces.first][indeces.second];
}
void setValue(int index,T value){
pair<int,int> indeces = position(index);
arr[indeces.first][indeces.second] = value;
}
int capacity(){
return maxSize;
}
int size(){
return currentIndex;
}
bool empty(){
return currentIndex==0?true:false;
}
PS: I tried to use Valgrind, but failed to identify the exact problem.
Your program leaks memory because you never free the pointers in a destructor. You must implement a destructor to solve your memory leak (in addition to a move constructor, copy constructor, assignment copy, and assignment move).
In addition to valgrind, you can use ASAN which has better output and also runs faster.
The main problem of your code that leads your code to crash isn't memory leak. Totally memory leak doesn't leads to crash in short term. in memory leak case your application works until there is enough space on your RAM and then if your RAM being full , crash occurs. you make a mistake in position() method in finding second dimension index.
For example when you call position(index:29) because of implementation of float and float precision result of (result - pos.first)*b is 9.00000095. It means its result has a little difference with real result(9). and then you call ceil(9.00000095) and it return 10 for result. It means you access index 10 for your second dimension whereas you can use index from 0 to 9 and you have index out of range access that leads you to crash after some period of time and your program may have undefined behavior.
the correct sample for position method is :
pair<int, int> position(int index){
pair<int, int> pos;
float result = ((float)index / b);
pos.first = result; //Row #
pos.second = index%b; // changed line
return pos;
}
Finally you should define destructor and delete all memories you allocated by new operator. All of vector element(arrays) need to be deleted.
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> result;
queue<TreeNode *> que;
if (root != nullptr) {
que.emplace(root);
}
while (!que.empty()) {
vector<int> level;
int size = que.size();
for (int i = 0; i < size; i++) {
auto *front = que.front();
que.pop();
level.emplace_back(front->val);
if (front->left != nullptr) {
que.emplace(front->left);
}
if (front->right != nullptr) {
que.emplace(front->right);
}
}
result.emplace_back(move(level));
}
return result;
}
Problem: https://leetcode.com/problems/binary-tree-level-order-traversal/description/
Above is the function that returns a vector>.
However, since I initialized the vector as a local variable vector<vector<int>> result; does it mean that it is a code smell for me to return it?
Since the vector is a local variable, it is allocated on the stack and the vector will get destroyed when this function call is over.
Should I have done this instead auto results = new vector<vector<int>>
No.
Since the software will not allow me to stop at that, I will elaborate. The "No" applies to the question only. I have not checked the code for errors. So, no, it is not wrong to return the result as written. There is no cost involved. Any modern compiler will use return-value optimization to return the result.
It would be very bad form to use operator new. Doing so would put the burden of deleting the object upon the calling function. Search for "C++ RAII".
#include<iostream>
#include<vector>
using namespace std;
class Stack
{
public:
int top;
vector<int> v;
Stack(int size)
{
top=0;
cout<<"Enter the values"<<endl;
for(int i=0; i<size; i++)
{
int val;
cin>>val;
v.push_back(val);
top++;
}
}
void push(int val)
{
v.push_back(val);
top++;
}
int pop()
{
int x=v[top];
top--;
return x;
}
void disp()
{
for(int j=top; j<=0; j--)
cout<<v[j]<<' ';
}
};
int main()
{
Stack s(3);
int k=s.pop();
cout<<k;
return 0;
}
I am trying to learn the basics of OOP.
Here, my Stack constructor and push function are working fine, but there is a problem with the pop and disp functions.
I'm assuming that I am using an incorrect syntax to access the elements of a vector(maybe?). Can anyone tell me where I am going wrong?
Also, the value of k always comes out to be 0.
You can use the vector functions
int k = s.back();
s.pop_back();
cout << k;
more informationhttp://www.cplusplus.com/reference/vector/vector/back/
You have a off-by-one index error.
The way you have implemented your class, when there are N items in the stack, the value of top is N.
Hence, top is not a valid index to access the elements of v. You can use:
int pop()
{
int x=v[top-1];
top--;
return x;
}
or
int pop()
{
top--;
int x=v[top];
return x;
}
As some of the other answers say, you can use the built-in vector functions to do these things (see pop_back and back.
However, if you want to define your own, I would use the vector.at(index) function. Addressing the values with the index as you have works, but it doesn't do any bounds checking at() does. Which would solve your problem above where your index isn't correct for the zero-based indexing of a vector.
I am using a vector of vector in my A3 code. I sort the vector of vector's at insertion. I store my keys in the 0th index of each sub vector.
In my size method, I am trying to use the direct call for checking the size. The code below outlines my attempt. However, I get a segmentation fault on execution. Can anyone help me understand the reason for the same?
vector<vector<int>> pairs; //sorted in the insert method
int size(int key) const {
if( pairs[key].size() == 0 ) { return -1; }
else { return pairs[key].size() - 1; }
}
I have implemented the same successfully previously, however, it was a very inefficient solution using linear search. Here is the code for the same:
int size(int key) const
{
for( int i=0; i<pairs.size(); i++)
{
if( pairs[i][0] == key )
{
return pairs[i].size() - 1;
}
}
return -1;
}
This code is not enough to tell you what is happening, we can only make a guess.
I would say that your leak comes from the method data: you create a copy of the data and then return a pointer to this copy. It would be better to return an unique_ptr, so the memory is released automatically.
If you cannot change the definition of the method, then you could change the body of the method by this one:
int length = size(key);
if( length == -1 )
return nullptr;
for( int i=0; i<pairs.size(); i++)
{
if( pairs[i][0] == key )
{
return &pairs[i][1];
}
}
return nullptr;
I have a recursive function, that is returning a list of structs.
struct Neighbour_node{
int index;
double dist;
};
And here is the function:
list<Neighbour_node> findNewNeighbours(int original, int particle, int k){
Neighbour_node node;
list<Neighbour_node> neighbours;
list<Neighbour_node> temp_neighbours;
list<Neighbour_node>::iterator iterator;
if (k <= 0){
if (particle == -1){
node.index = -1;
node.dist = 1000.0;
}
else{
node.index = particle;
node.dist = glm::length(hair[original].position - hair[particle].position);
neighbours.push_back(node);
}
}
else {
for (unsigned int i = 0; i < hair[particle].neighbours.size(); i++){
temp_neighbours = findNewNeighbours(original,hair[particle].neighbours[i],k - 1);
temp_neighbours.sort(compareNeighbour_node);
neighbours.merge(temp_neighbours,compareNeighbour_node);
}
}
return neighbours;
}
Line:
temp_neighbours = findNewNeighbours(original,hair[particle].neighbours[i],k - 1);
causes segmentation fault and I am not sure why. I have seen examples with line similar to my erroneous one and it seems, it is not wrong. But those functions were not recursive, so I am guessing that this is where the problem is - besides, when k = 0 (only one call of a function - thus as if it wasn't recursive), then it doesn't crash. Can anyone, please, help me with this?
Thanks
Check the stack size in your os.
ulimit -s
I suggest that it is because of stack.
Becase the stack you need seems increase rapidly.
Show your "hair" for more detail for us to see.