Why I am getting this? [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
29==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000000478 at pc 0x0000003a5517 bp 0x7ffe2f5c2670 sp 0x7ffe2f5c2668
Here is my code:
class Solution {
public:
vector summaryRanges(vector& nums) {
if(nums.size() == 0)
return {};
if(nums.size() == 1)
return {to_string(nums[0])};
vector<string> ans{};
int i=0,j=1,initial=nums[0];
if(nums.empty()||nums.size()==0)
return ans;
while(j<=nums.size())
{
if(i<nums.size())
{
if(nums[i]+1==nums[j])
{
i++;
j++;
}
else
{
string str3;
if(initial!=nums[i])
{
string str = to_string(initial);
string str1= to_string(nums[i]);
string str2 = "->";
str3=str+str2+str1;
}
else
{
str3 = to_string(initial);
}
ans.push_back(str3);
initial=nums[j];
i=j;
j++;
}
}
else
{
string str = to_string(initial);
ans.push_back(str);
}
}
return ans;
}
};

I think you are accessing an index out of vector size . Index j is probably going out of bounds .
while(j< = nums.size())
and
nums[j]

This
while(j<=nums.size())
and these
if(nums[i]+1==nums[j])
...
initial=nums[j];
look very suspicious. If j == nums.size() then nums[j] is an out of bounds error on num. Maybe you meant this?
while(j<nums.size())
(I.e. the same as you have with the i variable).

Related

Why is my code for prefix to infix not displaying an output [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I am writing this code on Visual studio 2019 which converts a prefix number to infix.
When i press F5 the window says: (process 10428) exited with code 0.
To automatically close the console when debugging stops, enable Tools->Options->Debugging->Automatically close the console when debugging stops.
I don't know much about C++. I know Java and python fairly well but our instructor wants us to use C++.
string s[7];
int f = -1;
void push(string a)
{
s[f++] = a;
}
string pop()
{
return s[f--];
}
bool isop(char x) {
switch (x)
{
case '+':
case '-':
case '*':
case '/':
return true;
}
return false;
}
int main() {
string a = "*+ab+cd";
reverse(a.begin(), a.end());
for (int i = 0;i<int(a.length());i++) {
if (isop(a[i])) {
string v1 = pop();
string v2 = pop();
string h = "(" + v1 + a[i] + v2 + ")";
push(h);
}
else {
push(string(1, a[i]));
}
}
for (int i = 0;i < 7;i++)
{
cout << s[i];
}
return 0;
}
Problem here (it would be exactly the same in Java)
string s[7];
int f = -1;
void push(string a)
{
s[f++] = a;
}
The first time you push f is -1 so you have an out of bounds array access. I guess you meant this
void push(string a)
{
s[++f] = a;
}
You could have avoided this error by using a std::vector (similar to an ArrayList in Java).

Postfix notation stack C++ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am new to C++ and I want to use a stack to evaluate an expression given as an input (2+3*5+4 for example), containing only numbers, + and *. I wrote this code but it gives me Segmentation fault: 11. Could you please help me solve this or give me a hint about what could be wrong? Thank you! (I noticed there were similar questions on this site, but I couldn't use them to solve my problem)
#include <iostream>
#include <stack>
using namespace std;
bool highPrecedence(char a, char b){
if((a=='+')&&(b=='*'))
return true;
return false;
}
int main()
{
char c = 'a';
double x;
stack<char> stack;
double v[10];
int i=0;
double res;
while(true)
{
c = cin.get();
if(c=='\n'){
while(stack.size()!=0){
if (stack.top()=='*'){
double res = v[i]*v[i-1];
i--;
v[i]=res;
stack.pop();
}
if (stack.top()=='+'){
res = v[i]+v[i-1];
i--;
v[i]=res;
stack.pop();
}
}
break;
}
if ( '0'<=c && c<='9' )
{
cin.putback(c);
cin>>x;
cout<<"Operand "<<x<<endl;
i=i+1;
v[i]=x;
}
else
{
if(c!=' ') cout<< "Operator " <<c<<endl;
if (stack.size()==0)
stack.push(c);
else{
while((!highPrecedence(stack.top(),c)) && (stack.size()!=0)){
if (stack.top()=='*'){
double res = v[i]*v[i-1];
i--;
v[i]=res;
stack.pop();
}
if (stack.top()=='+'){
res = v[i]+v[i-1];
i--;
v[i]=res;
stack.pop();
}
}
stack.push(c);
}
}
}
cout<<v[0]<<endl;
}
Using stack.top() is illegal if the stack is empty.
Change while((!highPrecedence(stack.top(),c)) && (stack.size()!=0)){
to while((!stack.empty()) && (!highPrecedence(stack.top(),c))){
The initiali value of i is not good and you are printing uninitialized variable, which has indeterminate value.
Change int i=0; to int i=-1;

Strangeness with dynamic arrays in C++ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am honestly not quite sure what is going on here.
It has been years since I have programmed in C++, but I am trying to execute this code
short* result = new short[3];
now, I would expect that this creates an array with 3 memory locations: 0,1 and 2, but for what ever reason, this works:
result[0] = someObject::parseShort();
but this does not work:
result[1] = someObject::parseShort();
no exception is thrown, but it is like addresses 1 and 2 dont even exist? I have verified this with visual studio's debugger, and this is leading to some very interesting results when I try to read from those memory addresses, no matter what I Initially wrote to them, they always seem to return 0
Like I said, its been years since I've written anything in C++, and would appreciate someone being able to tel me what is going on? because as far as I can tell, it looks like I am defining the array right?
EDIT:
here is the rest of the relevent code:
phoneNumber::phoneNumber(string number)
{
short* nbrs = parseNumber(number);
areaCode = nbrs[0];
prefix = nbrs[1];
this->number = nbrs[2];
delete[] nbrs;
}
areaCode, prefix, and number are all members of the class.
area code gets set correctly, but prefix and number dont seem to
here is the definition of parseNumber:
short* phoneNumber::parseNumber(string num)
{
if (num == "")
throw new exception("value should not be null");
int var= 3;
short* result= new short[var];
string temp = "";
bool fail = false;
int j = 0;
bool ready = false;
num = Utils::removeSpaces(num);
if (j ==0&&num[0] != '(')
{
fail = true;
}
for (int i = 1; i < num.length(); i++)
{
if (fail)
{
throw exception("Could not parse phone number! Invalid format, expected (xxx)xxx-xxxx");
}
if (num[i] >= '0' && num[i] <= '9')
{
temp+=num[i];
continue;
}
else if (j== 0 && num[i] ==')')
{
if(temp.length() != 3)
{
fail = true;
continue;
}
ready = true;
}
else if(j==1 && num[i] =='-')
{
if(temp.length() != 3)
{
fail = true;
continue;
}
ready = true;
}
else if (j == 3 && i == num.length() -1)
{
if(temp.length() != 4)
{
fail = true;
continue;
}
ready = true;
}
else
{
fail = true;
continue;
}
if (ready)
{
result[j]= Utils::parseShort(temp);
j++;
temp = "";
ready = false;
continue;
}else
{
temp+= num[i];
}
}
if (temp.length()==4)
result[j]= Utils::parseShort(temp);
else
{
throw exception("Could not parse phone number! Invalid format, expected (xxx)xxx-xxxx");
}
return result;
}
Yes, you are defining your array right. You have a bug elsewhere in your code outside the part that constitutes your question.

Sorting list. What is wrong with my sorting method? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I have a real headache with my sorting method. I don't know what can be wrong? I have checked sorting method millions of times and I still messed up with it.
Here are my code
struct Man{
string name;
string adress;
bool operator < (const Man & next);
};
bool Man::operator < (const Man & next){
return adress < next.adress && name < next.name;
}
struct SarV{
Man duom;
SarV *sekV;
};
struct SarH{
string date;
SarH *sekH;
SarV *prV;
};
void Branch::Check(string code, int month){
ofstream rf("Rezultatai.txt", ios::app);
rf.setf(ios::left);
SarH *d = pr;
rf << "Data" << endl;
while(d != NULL){
SarV *v = d->prV;
Print(rf, v, code, month);
d = d->sekH;
}
rf.close();
}
Here are my sorting function
void Branch::Sort(){
string temp;
for(SarH *s = pr; s != NULL; s = s->sekH){
for(SarV *p = s->prV; p != NULL; p = p->sekV){
for(SarV *p2 = p; p2 != NULL; p2 = p2->sekV){
if(p2->duom < p->duom){
//---------------------------------------
temp = p->duom.name;
p->duom.name = p2->duom.name;
p2->duom.name = temp;
//---------------------------------------
temp = p->duom.adress;
p->duom.adress = p2->duom.adress;
p2->duom.adress = temp;
//---------------------------------------
}
}
}
}
}
So what's wrong with it?
Your operator is likely wrong.
Try this:
bool Man::operator < (const Man & next){
if(adress < next.adress) return true;
if(adress == next.adress) {
if(name < next.name) return true;
}
return false;
}

Base changing algorithm in c++/c [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have the following function:
template <class T>
T c_base (T num,T second, T first = 10)
{
T res = 0;
T secnum;
T bitseed[90];
int i = 1,k,jump,anex,len;
if(second==first)
{
res = num;
return (res);
}
if(first==10&&second!=10)
{
anex = num;
while(num>0)
{
jump = num/second;
bitseed[i] = num%second;
num/=second;
i++;
}
if(anex>0)
{
for(k=i;k>=1;k--)
{
if(k==i&&jump==0) {res = bitseed[k-1]; k--; continue;}
if(k==i&&jump!=0) {res = jump; continue;}
res = res*10+bitseed[k];
}
}
return (res);
}
if(second==10)
{
anex = num;
len = 1;
while(anex>=10)
{
len *= 10;
anex/=10;
i++;
}
anex = num;
if(anex>0)
{
for(k=i;k>=1;k--)
{
res = res*first+anex/len;
anex%=len;
len/=10;
}
}
return (res);
}
if(second!=10&&first!=10)
{
secnum = c_base <T> (num,10,first);
res = c_base <T> (secnum,second,10);
return (res);
}
}
I was wondering how efficient it is (from both speed and memory consumed point of view) and how/if can it be improved. (from the algorithm perspective)
Ps. Explication of function : c_base("number","to-base","from-base"->optional);
I see a lot of confusion here:
A number doesn't have a base. What do have bases are number representations. Both input and output should be number representations (e.g. std::strings in C++).
Why treating base 10 specially? there's nothing really special about it except that by historical accidents most humans today use it. This is totally irrelevant for an algorithm. A special case for power-of-two bases could make sense for technical reasons (because computers use base 2 internally).
Why doing a double conversion instead of just reading from base x and writing to base y?