I was solving the climbing leaderboard problem in hackerrank but my function gives segmentation fault.
vector<int> climbingLeaderboard(vector<int> scores, vector<int> alice) {
vector<int> res,i;
auto ip= unique(scores.begin(),scores.begin()+scores.size());
scores.resize(distance(scores.begin(),ip));
for(int i =0;i<alice.size();++i)
{
int curr =0;
while(alice[i]<=scores[curr]&&curr<scores.size())
++curr;
if(alice[i]==scores[curr-1])
res[i]=curr-1;
else if(alice[i]>scores[curr])
res[i]=curr;
else if(curr>scores.size()-1)
res[i]=curr;
}
return res;
}
It gives the following error:
> Program terminated with signal SIGSEGV, Segmentation fault.
> #0 0x0000000000402a01 in climbingLeaderboard (scores=..., alice=...)
> at /usr/local/include/c++/8.3.0/bits/stl_vector.h:930 930 operator[](size_type __n) _GLIBCXX_NOEXCEPT
Firstly, res[i] is accessed without allocating any elements in res.
vector<int> res should be vector<int> res(alice.size()).
Secondly, scores[curr] may be accessed before checking if curr<scores.size().
while(alice[i]<=scores[curr]&&curr<scores.size())
++curr;
should be
while(curr<scores.size()&&alice[i]<=scores[curr])
++curr;
and
else if(alice[i]>scores[curr])
res[i]=curr;
else if(curr>scores.size()-1)
res[i]=curr;
should be
else if(curr>scores.size()-1)
res[i]=curr;
else if(alice[i]>scores[curr])
res[i]=curr;
Related
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.
I am getting segmentation fault for some unknown test case and I am unable to resolve it.
It runs for most of the cases. I only want to know in which case I am getting segmentation fault.
The code is written for the Question Maximim Rectangular Area in a Histogram. You can check this question here: https://practice.geeksforgeeks.org/problems/maximum-rectangular-area-in-a-histogram-1587115620/1#
Below is the code:
long long getMaxArea(long long arr[], int n)
{
int nsl[n];
int nsr[n];
stack<int>s;
// nsl
for(int i=0;i<n;i++)
{
if(i==0)
{
nsl[i]=-1;
s.push(i);
}
else{
while(!s.empty())
{
if(arr[s.top()]<arr[i])
break;
s.pop();
}
if(s.empty())
nsl[i]=-1;
else
nsl[i]=s.top();
s.push(i);
}
}
stack<int>st;
// nsr
for(int i=n-1;i>=0;i--)
{
if(i==n-1)
{
nsr[i]=n;
st.push(i);
}
else{
while(!st.empty())
{
if(arr[st.top()]<arr[i])
break;
st.pop();
}
if(st.empty())
nsr[i]=n;
else
nsr[i]=st.top();
st.push(i);
}
}
long long ans=0;
for(int i=0;i<n;i++)
ans=max(ans,arr[i]*(nsr[i]-nsl[i]-1));
return ans;
}
The problem got solved by using vector instead of array. I was just using bad c++ syntax for array and hence using vector just solved it.
I have solved the parenthesis check problem in gfg. when I checked this code with custom input it's working fine and the output is matched . when I submit this code, it shows
Runtime Error: Runtime ErrorSegmentation Fault (SIGSEGV)
bool ispar(string x)
{
int n=x.length();
stack <char> s;
int i=0;
while(i<n)
{
if(x[i]=='['|| x[i]=='('|| x[i]=='{' )
s.push(x[i]);
else if (x[i]==']'&& s.top()=='['|| x[i]==')'&& s.top()=='('||x[i]=='}'&& s.top()=='{')
s.pop();
else
return 0;
i++;
}
return (s.empty());
You are doing s.top() without checking if s is empty. You should add check for that.
else if (!s.empty() && (x[i]==']'&& s.top()=='['|| x[i]==')'&& s.top()=='('||x[i]=='}'&& s.top()=='{'))
s.pop();
So my code worked for my lab on c++ memory errors, but although it worked I keep getting the "* Error in `./Drivers': free(): invalid next size (normal): 0x000000000166c2d0 *" error, and along with that comes the back trace and the memory map. So I was just wondering why such problem is occuring.
Here is my code:
int binarySearch(const Array<NYCTaxiDriver>& aSortedList,
unsigned int aKey,
int aBegin,
int aEnd
)
{
if(aEnd >= aBegin){
int avg = (aBegin+aEnd)/2;
if(aSortedList[avg].getMedallionNumber() == aKey){
return avg;
}
if(aSortedList[avg].getMedallionNumber()>aKey){
return binarySearch(aSortedList,aKey, aBegin, avg-1);
}
return binarySearch(aSortedList,aKey, avg+1, aEnd);
}
return -1;
}
void printTheMatchingDrivers(const Array<unsigned int>& aManhattanMedallions,const Array<NYCTaxiDriver>& aMatchedDrivers)
{
int size = aMatchedDrivers.getSize();
for(int i=0;i<aManhattanMedallions.getSize()-1;i++){
int resultPos = binarySearch(aMatchedDrivers,aManhattanMedallions[i],0,size);
if(resultPos != -1){
cout<<"Match "<<1<< ":"<<"\n"<<aMatchedDrivers[resultPos].getMedallionNumber()<<": "<<aMatchedDrivers[resultPos].getLastName()<<", "<<aMatchedDrivers[resultPos].getFirstName()<<endl;
}
}
}
int main(){
Array<unsigned int> manhattanMedallions;
Array<NYCTaxiDriver> matchedDrivers;// already sorted
printTheMatchingDrivers(manhattanMedallions, matchedDrivers);
return 0;
}
The issue seems to be in the container class Array.
I am creating an adjacency list for the graph structure.Below is my code snippet which
is giving "Program received signal SIGSEGV, Segmentation fault. 0x0040340f in std::_List_node_base::hook ()" error when I run in gdb. Could somebody please point out the error in the code.
struct graph{
list<int> vertex;
}*v;
list<int>::iterator it;
cin>>num_vertices;
v = new graph[num_vertices];
if (v == 0)
cout << "Error: memory could not be allocated";
for(i=1;i<=num_vertices;i++)
{
cin>>num_connected;
for(j=1;j<=num_connected;j++)
{
cin>>m;
(v+i)->vertex.push_back(m);
}
}
for(i=1;i<=num_vertices;i++)
for(it= (v+i)->vertex.begin();it!= (v+i)->vertex.end();it++)
cout<<*it<<"->";
C++ arrays are zero-based so should be indexed using [0] to [num_vertices-1]. If you change your loops to go from 0 to num_vertices-1
for(i=0;i<num_vertices;i++)
your code should work.
The current failures are presumably caused by the last iteration of the loops dereferencing (v+num_vertices) which is memory beyond your array. Writing to memory you haven't allocated gives undefined behaviour so a seg fault wouldn't be surprising.
I don't see anything wrong here, I compiled your program (just declared the variables you are using) and it works fine
#include <iostream>
#include <list>
using namespace std;
struct graph{
list<int> vertex;
}*v;
int main ()
{
int num_vertices = 0;
int num_connected = 0;
list<int>::iterator it;
cin>>num_vertices;
v = new graph[num_vertices];
if (v == 0)
cout << "Error: memory could not be allocated";
for(int i=0;i<num_vertices;i++)
{
cin>>num_connected;
for(int j=1;j<=num_connected;j++)
{
int m;
cin>>m;
(v+i)->vertex.push_back(m);
}
}
for(int i=0;i<num_vertices;i++)
for(it= (v+i)->vertex.begin();it!= (v+i)->vertex.end();it++)
cout<<*it<<"->";
}