runtime error: addition of unsigned offset to 0x602000000390 overflowed to 0x60200000038c - overflow

I was solving a question named as. Find First and Last Position of Element in Sorted Array
'''
void bin_search(vector<int>&nums,int target,int l,int h,int &a,int &b)
{
if(l>h)
return;
int mid= l + (h - l) / 2;
if(nums[mid]==target)
{
if(nums[mid-1]==target)
{
bin_search(nums,target,l,mid-1,a,b);
}
else
{
a=mid;
}
if(nums[mid+1]==target)
{
bin_search(nums,target,mid+1,h,a,b);
}
else
{
b=mid;
}
}
else if(nums[mid]<target)
{
bin_search(nums,target,mid+1,h,a,b);
}
else
{
bin_search(nums,target,l,mid-1,a,b);
}
}
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int a=-1;
int b=-1;
int l=0;
int h=nums.size()-1;
bin_search(nums,target,l,h,a,b);
return {a,b};
}
};
'''
this is the code which i submitted but i am getting
Line 1034: Char 34: runtime error: addition of unsigned offset to 0x602000000390 overflowed to 0x60200000038c (stl_vector.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/bits/stl_vector.h:1043:34
error i am able to pass all the test cases in my complier and other id but didn't able to solve this bug
please help me thanks in advance

Related

leetcode Runtime error: addition of unsigned offset

I was solving a question on Leetcode(Next Permutation)
class Solution {
public:
void nextPermutation(vector<int>& nums) {
int i=nums.size()-2;
while(i>=0 && nums[i]>nums[i+1])
{
i--;
}
int j=nums.size()-1;
if(i>=0)
{
while(j>=0 && nums[j]<=nums[i]){
j--;
}
swap(nums[i],nums[j]);
}
reverse(nums.begin()+i+1,nums.end());
}
};
This is the only part i had to edit. And upon running it i'm getting the following error
Line 1034: Char 34: runtime error: addition of unsigned offset to 0x602000000470 overflowed to 0x60200000046c (stl_vector.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:34
If nums = [1,1,1], the following code will be excute:
while(j>=0 && nums[j]<=nums[i]){
j--;
}
until j=-1, and the following code causes vector overflowed:
swap(nums[i],nums[j]);
and then this error message of yours appears.

Collect2: error reference method without defining

I'm building a basic program to make a list that consists of objects in c++, I've looked over the code several times and am just stuck, my professor isn't answering and have to turn this in soon, if anyone can help me find why it's saying that getTotal2020() is not defined when clearly it is. I am compiling with all the files and the #include is in all the files as well.
I've tried different ways of accessing this method but every time it throws errors. At least how I have the code now, I don't have any errors.
class Data {
public:
Data(string neighborhood, int total2020, int numOfMen, int numOfWomen);
string neighborhood;
int total2020;
int numOfMen;
int numOfWomen;
~Data();
string getNeighborhood();
int getTotal2020();
int getNumOfMen();
int getNumOfWomen();
};
Data::Data(string neighborhood, int total2020, int numOfMen, int numOfWomen) {
this->neighborhood;
this->total2020;
this->numOfMen;
this->numOfWomen;
}
string getNeighborhood(string neighborhood){
return neighborhood;
}
int getTotal2020(int total2020){
return total2020;
}
int getNumMen(int numOfMen){
return numOfMen;
}
int getNumOfWomen(int numOfWomen){
return numOfWomen;
}
class Node{
public:
Node* next;
Data* data;
Node(Node* next, Data* data){
this->next = next;
this->data = data;
}
Node* getNode(){
return next;
}
Data* getData(){
return data;
}
};
void List::findElement(int findMinPop){
Node* aux;
aux = head;
while(aux){
if(aux->getData()->getTotal2020() >= findMinPop){
cout << "The population is greater" << endl;
} else {
cout << "The populations is less than you were looking for" << endl;
}
aux = aux->next;
}
}
The error is gives me is:
/tmp/ccJeheba.o:main.cpp:(.text+0x3ed): referencia a `Data::getTotal2020()' sin definir (that the method is not defined)
/tmp/ccJeheba.o:main.cpp:(.text+0x3ed): reubicación truncada para ajustar: R_X86_64_PC32 contra el símbolo `Data::getTotal2020()' sin definir
collect2: error: ld devolvió el estado de salida 1

Why Numbers are getting printed in the form like "12-256" , "13-256" rather than 12,13 etc.?

I'm solving one of the algorithms problem from university to implemet queue using stacks.
I've got my logic right i guess but the numbers are getting printed in the form of 12-256, 13-256, 14-256 instead of 12,13,14.
Here's my C++ Code,
#include <iostream>
using namespace std;
class Stack{
private:
int arr[200];
int tos = -1;
public:
bool empty(){
return (tos == -1)?true:false;
}
void push(int element){
arr[++tos] = element;
}
int pop(){
return arr[tos--];
}
void show(){
if(tos == -1){
cout<<"stack empty";
}else{
for(int i=tos;i>0;i--)
cout<<arr[i]<<"\t";
}
}
};
class Queue{
private:
Stack s1,s2;
public:
void enQueue(int x){
//just using s1 to add new elements
s1.push(x);
}
int deQueue(){
if(s1.empty())
throw 'e';
else{
int e;
while(!s1.empty()){
e = s1.pop();
s2.push(e);
}
cout<<"\nelement to be removed:"<<s2.pop();
if(s2.empty())
throw 'f';
else{
int e;
while(!s2.empty()){
e = s2.pop();
s1.push(e);
}
}
}
}
};
int main()
{
try{
Queue q1;
q1.enQueue(12);
q1.enQueue(13);
q1.enQueue(14);
q1.enQueue(15);
cout<<q1.deQueue();
cout<<q1.deQueue();
cout<<q1.deQueue();
cout<<q1.deQueue();
}catch(char c){
cout<<"\nstack empty!";
}
return 0;
}
I'm basically a Python Guy so i'm not able to figure out what's wrong with this code.
I'm new to C++, so please guide me through this.
Thanks in advance!
deQueue suffers from the following problems.
It doesn't return anything.
It's OK for s2 to be empty after its top has been popped.
Here's an updated version that should work.
int deQueue(){
if(s1.empty())
throw 'e';
int e;
while(!s1.empty()){
e = s1.pop();
s2.push(e);
}
int ret = s2.pop();
cout<<"\nelement dequeued:"<< ret;
// This is not correct.
// It's OK for s2 to be empty after its top has been popped.
// if(s2.empty())
// throw 'f';
while(!s2.empty()){
e = s2.pop();
s1.push(e);
}
return ret;
}
Suggestion for further improvement
Queue does not need two Stack objects as member variables. s2 can be a function local variable in deQueue.
class Queue
{
private:
Stack s;
...
};
If you decide to make that change, you'll have to update enQueue and deQueue accordingly.

Debug Assertion Error as soon as I take the input. Something wrong with "delete"?

I am having debug assertion error as soon as I input two elements. The program was giving me access reading or sometimes writing violation error after taking 7-8 entries but after I deleted the dynamic array, it is showing debug assertion failed after taking first two inputs and breaks down. Any idea for how to solve it? I am copying only my air class here. I have similar Fire, earth and water classes too.
The error is BLOCK_TYPE_IS_VALID (pHead->nBlockUse)
Someone else too asked this question but i can't figure out My program errors. Kindly help would be appreciated.
#ifndef AIR_H
#define AIR_H
#include <iostream>
#include <string>
#include "element.h"
using namespace std;
class Air :public Element
{
public:
string air;
string Elements [2];
int i;
string *elements;
public:
Air(string n): Element (n)
{
air = n;
i=-1;
elements = new string[2];
}
void alreadyExists (string a)
{
int lineCount = 0;
ifstream read;
read.open ("Air.txt", ios::in | ios::app);
while(!read.eof())
{
string x;
read>>x;
lineCount++;
}
lineCount--;
read.close();
read.open("Air.txt", ios::in|ios::app);
for(int i = 0; i < lineCount; i++)
{
read>>elements[i];
}
bool Found = false;
for(int i = 0; i < lineCount; i++) {
if(a == elements[i])
{
Found = true;
break;
}
}
if(!Found)
{
write2file (a);
}
}
void write2file (string air)
{
ofstream write;
write.open ("Air.txt", ios::out|ios::app);
{
write<<air<<endl;
}
}
void DisplayA ()
{
/*for(int i=0; i<2; i++)//( to read through the arrays )
{
cout<<Elements[i]<<endl;
}*/
ifstream read ("Air.txt", ios::in|ios::app);
int i=0;
while (read >> Elements[i])
{
cout<<Elements[i]<<endl;
}
}
Air operator+(Air & air)
{
Air newElement ("NULL");
if (this->air == "Air"||this->air=="air"&& air.air == "Air"||air.air=="air")
{
newElement.air = "Pressure";
cout<<"Yay!! You've made: "<<newElement.air<<endl;
alreadyExists (newElement.air);
//PushA (newElement.air);
//write2file (newElement.air);
return newElement;
}
else if ((this->air == "Air"||this->air == "air") && (air.air == "Pressure"||air.air=="pressure"))/* || ((this->air == "Pressure"||this->air=="pressure") && ( air.air == "Air"||air.air=="air")))*/
{
newElement.air = "Atmosphere";
cout<<"Wuhooo!! You've made: "<<newElement.air<<endl;
alreadyExists (newElement.air);
//PushA (newElement.air);
//write2file (newElement.air);
return newElement;
}
else return newElement;
}//pressure, atmosphere
~ Air ()
{
delete []elements;
}
};
#endif
BLOCK_TYPE_IS_VALID (pHead->nBlockUse)
Assertion means a corrupt heap at deleting/clearing.
As far as I see, you missed the virtual deconstructor of Element.
Try something like:
virtual ~Element() {}
in class Element.
And please post also the Element class.
Good luck!

Looking at Sorts - Quicksort Iterative?

I'm looking at all different sorts. Note that this is not homework (I'm in the midst of finals) I'm just looking to be prepared if that sort of thing would pop up.
I was unable to find a reliable method of doing a quicksort iteratively. Is it possible and, if so, how?
I'll try to give a more general answer in addition to the actual implementations given in the other posts.
Is it possible and, if so, how?
Let us first of all take a look at what can be meant by making a recursive algorithm iterative.
For example, we want to have some function sum(n) that sums up the numbers from 0 to n.
Surely, this is
sum(n) =
if n = 0
then return 0
else return n + sum(n - 1)
As we try to compute something like sum(100000), we'll soon see this recursive algorithm has it's limits - a stack overflow will occur.
So, as a solution, we use an iterative algorithm to solve the same problem.
sum(n) =
s <- 0
for i in 0..n do
s <- s + i
return s
However, it's important to note that this implementation is an entirely different algorithm than the recursive sum above. We didn't in some way modify the original one to obtain the iterative version, we basically just found a non-recursive algorithm - with different and arguably better performance characteristics - that solves the same problem.
This is the first aspect of making an algorithm iterative: Finding a different, iterative algorithm that solves the same problem.
In some cases, there simply might not be such an iterative version.
The second one however is applicable to every recursive algorithm. You can turn any recursion into iteration by explicitly introducing the stack the recursion uses implicitly. Now this algorithm will have the exact same characteristics as the original one - and the stack will grow with O(n) like in the recursive version. It won't that easily overflow since it uses conventional memory instead of the call stack, and its iterative, but it's still the same algorithm.
As to quick sort: There is no different formulation what works without storing the data needed for recursion. But of course you can use an explicit stack for them like Ehsan showed. Thus you can - as always - produce an iterative version.
#include <stdio.h>
#include <conio.h>
#define MAXELT 100
#define INFINITY 32760 // numbers in list should not exceed
// this. change the value to suit your
// needs
#define SMALLSIZE 10 // not less than 3
#define STACKSIZE 100 // should be ceiling(lg(MAXSIZE)+1)
int list[MAXELT+1]; // one extra, to hold INFINITY
struct { // stack element.
int a,b;
} stack[STACKSIZE];
int top=-1; // initialise stack
int main() // overhead!
{
int i=-1,j,n;
char t[10];
void quicksort(int);
do {
if (i!=-1)
list[i++]=n;
else
i++;
printf("Enter the numbers <End by #>: ");
fflush(stdin);
scanf("%[^\n]",t);
if (sscanf(t,"%d",&n)<1)
break;
} while (1);
quicksort(i-1);
printf("\nThe list obtained is ");
for (j=0;j<i;j++)
printf("\n %d",list[j]);
printf("\n\nProgram over.");
getch();
return 0; // successful termination.
}
void interchange(int *x,int *y) // swap
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
void split(int first,int last,int *splitpoint)
{
int x,i,j,s,g;
// here, atleast three elements are needed
if (list[first]<list[(first+last)/2]) { // find median
s=first;
g=(first+last)/2;
}
else {
g=first;
s=(first+last)/2;
}
if (list[last]<=list[s])
x=s;
else if (list[last]<=list[g])
x=last;
else
x=g;
interchange(&list[x],&list[first]); // swap the split-point element
// with the first
x=list[first];
i=first+1; // initialise
j=last+1;
while (i<j) {
do { // find j
j--;
} while (list[j]>x);
do {
i++; // find i
} while (list[i]<x);
interchange(&list[i],&list[j]); // swap
}
interchange(&list[i],&list[j]); // undo the extra swap
interchange(&list[first],&list[j]); // bring the split-point
// element to the first
*splitpoint=j;
}
void push(int a,int b) // push
{
top++;
stack[top].a=a;
stack[top].b=b;
}
void pop(int *a,int *b) // pop
{
*a=stack[top].a;
*b=stack[top].b;
top--;
}
void insertion_sort(int first,int last)
{
int i,j,c;
for (i=first;i<=last;i++) {
j=list[i];
c=i;
while ((list[c-1]>j)&&(c>first)) {
list[c]=list[c-1];
c--;
}
list[c]=j;
}
}
void quicksort(int n)
{
int first,last,splitpoint;
push(0,n);
while (top!=-1) {
pop(&first,&last);
for (;;) {
if (last-first>SMALLSIZE) {
// find the larger sub-list
split(first,last,&splitpoint);
// push the smaller list
if (last-splitpoint<splitpoint-first) {
push(first,splitpoint-1);
first=splitpoint+1;
}
else {
push(splitpoint+1,last);
last=splitpoint-1;
}
}
else { // sort the smaller sub-lists
// through insertion sort
insertion_sort(first,last);
break;
}
}
} // iterate for larger list
}
// End of code.
taken from here
I was unable to find a reliable method of doing a quicksort iteratively
Have you tried google ?
It is just common quicksort, when recursion is realized with array.
This is my effort. Tell me if there is any improvement possible.
This code is done from the book "Data Structures, Seymour Lipschutz(Page-173), Mc GrawHill, Schaum's Outline Series."
#include <stdio.h>
#include <conio.h>
#include <math.h>
#define SIZE 12
struct StackItem
{
int StartIndex;
int EndIndex;
};
struct StackItem myStack[SIZE * SIZE];
int stackPointer = 0;
int myArray[SIZE] = {44,33,11,55,77,90,40,60,99,22,88,66};
void Push(struct StackItem item)
{
myStack[stackPointer] = item;
stackPointer++;
}
struct StackItem Pop()
{
stackPointer--;
return myStack[stackPointer];
}
int StackHasItem()
{
if(stackPointer>0)
{
return 1;
}
else
{
return 0;
}
}
void ShowStack()
{
int i =0;
printf("\n");
for(i=0; i<stackPointer ; i++)
{
printf("(%d, %d), ", myStack[i].StartIndex, myStack[i].EndIndex);
}
printf("\n");
}
void ShowArray()
{
int i=0;
printf("\n");
for(i=0 ; i<SIZE ; i++)
{
printf("%d, ", myArray[i]);
}
printf("\n");
}
void Swap(int * a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int Scan(int *startIndex, int *endIndex)
{
int partition = 0;
int i = 0;
if(*startIndex > *endIndex)
{
for(i=*startIndex ; i>=*endIndex ; i--)
{
//printf("%d->", myArray[i]);
if(myArray[i]<myArray[*endIndex])
{
//printf("\nSwapping %d, %d", myArray[i], myArray[*endIndex]);
Swap(&myArray[i], &myArray[*endIndex]);
*startIndex = *endIndex;
*endIndex = i;
partition = i;
break;
}
if(i==*endIndex)
{
*startIndex = *endIndex;
*endIndex = i;
partition = i;
}
}
}
else if(*startIndex < *endIndex)
{
for(i=*startIndex ; i<=*endIndex ; i++)
{
//printf("%d->", myArray[i]);
if(myArray[i]>myArray[*endIndex])
{
//printf("\nSwapping %d, %d", myArray[i], myArray[*endIndex]);
Swap(&myArray[i], &myArray[*endIndex]);
*startIndex = *endIndex;
*endIndex = i;
partition = i;
break;
}
if(i==*endIndex)
{
*startIndex = *endIndex;
*endIndex = i;
partition = i;
}
}
}
return partition;
}
int GetFinalPosition(struct StackItem item1)
{
struct StackItem item = {0};
int StartIndex = item1.StartIndex ;
int EndIndex = item1.EndIndex;
int PivotIndex = -99;
while(StartIndex != EndIndex)
{
PivotIndex = Scan(&EndIndex, &StartIndex);
printf("\n");
}
return PivotIndex;
}
void QuickSort()
{
int median = 0;
struct StackItem item;
struct StackItem item1={0};
struct StackItem item2={0};
item.StartIndex = 0;
item.EndIndex = SIZE-1;
Push(item);
while(StackHasItem())
{
item = Pop();
median = GetFinalPosition(item);
if(median>=0 && median<=(SIZE-1))
{
if(item.StartIndex<=(median-1))
{
item1.StartIndex = item.StartIndex;
item1.EndIndex = median-1;
Push(item1);
}
if(median+1<=(item.EndIndex))
{
item2.StartIndex = median+1;
item2.EndIndex = item.EndIndex;
Push(item2);
}
}
ShowStack();
}
}
main()
{
ShowArray();
QuickSort();
ShowArray();
}

Resources