matrix rotation segmentation fault - c++

Writing code for the matrix rotation question in hackerrank. i am getting segmentation fault. the code is not complete. i have commented on the statements which i think is creating the prblem but cant identify the mistake . plz help.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
struct coord
{
int i,j;
} starting, current;
struct reference
{
float i,j;
} center;
int **a,m,n,t1,t2;
int goup()
{
float dist,dist2;
dist=sqrt((center.i-current.i)*(center.i-current.i)+(center.j-current.j)*(center.j-current.j));
do
{
t1=a[current.i-1][current.j];
a[current.i-1][current.j]=t2;//segmentation fault at this statement
t2=t1;
current.i--;
dist=sqrt((center.i-current.i)*(center.i-current.i)+(center.j-current.j)*(center.j-current.j));
} while(dist2!=dist);
return 0;
}
int main()
{
int t;
cin>>m>>n>>t;
a=new int*[m];
for(int i=0;i<m;i++)
a[i]=new int[n];
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
cin>>a[i][j];
center.i=(float)(m-1)/2.0;
center.j=(float)(n-1)/2.0;
starting.i = center.i + (0.5)*(m%2+1);
starting.j = center.j + (0.5)*(n%2+1);
current.i=starting.i;
current.j=starting.j;
t2=a[starting.i][starting.j];
t1=a[starting.i-1][starting.j];
while(current.i!=m)
{
for(int i=0;i<t;i++)
{
goup();
// goleft();
// godowm();
// goright();
}
starting.i++;
starting.j++;
current.i=starting.i;
current.j=starting.j;
}
return 0;
}

Since dist2 is never initialised, dist2!=dist is rarely true and you decrement current.i so many times that you wind up accessing outside the array and dereferencing whatever random number might be lying around there.
It's impossible to say how to fix it since you haven't left any clue about what the function is supposed to accomplish.
Initialising dist2 with whatever value you want it to have would be a good start, but the condition is still unlikely to ever be true.

Related

A problem of ending the implementation of the code

this code works well for all samples, but after all samples are finished, a problem occurs. I don’t know what happens and the program crashes. Is there a problem with this code?
i have this problem when i use strings arrays usualy can it be the problem?
#include <iostream>
#include <vector>
#include <utility>
#include <algorithm>
#include <bits/stdc++.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
long long t,n;
int a[1000];
string str[1000];
int main()
{
cin>>t;
for(int r=1;r<=t;r++){
cin>>n;
int maxi=0;
for(int i=1;i<=n;i++){
cin>>a[i];
if(a[i]>maxi)maxi=a[i];
};
//input first value
maxi=maxi+3;
for(int r1=0;r1<maxi;r1++){
str[1][r1]=(rand()%26)+'a';
}
for(int i=0;i<maxi;i++){
cout<<str[1][i];
}
cout<<endl;
//
for(int k=2;k<=(n+1);k++){
int w;
for(w=0 ; w<=a[k-1];w++){
str[k][w]=str[k-1][w];
};
for(int l=w-1;l<maxi;l++){
str[k][l]=(rand()%26)+'a';
};
for(int i=0;i<maxi;i++){
cout<<str[k][i];
}
cout<<endl;
}
}
return 0;
}
You are using elements of strings without allocating them.
Allocate elements by inserting
for(int i=1;i<=(n+1);i++){
str[i].resize(maxi);
}
just after
maxi=maxi+3;

Recursive function, which writes integer digits in an array(vector) in C++?

I have a C++ program, in which I have to create a recursive function that writes all the digits of a given positive integer in an array - in this case a vector.
However, when I compile the program and enter a number, it stops working. I want to ask why this happens?
#include <iostream>
#include <vector>
using namespace std;
vector <int> arr;
int temp;
int fill_Array(int num)
{
if(num>=1 && num<=9)
{
arr.push_back(num);
}
temp = fill_Array(num)%10;
arr.push_back(temp);
num/=10;
}
int main()
{
int n;
cin>>n;
fill_Array(n);
for(int i=0; i<arr.size(); i++)
{
cout<<arr[i]<<endl;
}
return 0;
}
In the given code, recursion function does not returning any value, so return type for that function have no use.
calling the function for recursion is in the wrong place. Correct code given below:
#include <iostream>
#include <vector>
using namespace std;
vector <int> arr;
int temp;
void fill_Array(int num)
{
if(num>=1 && num<=9)
{
arr.push_back(num);
}
else{
temp = num%10;
arr.push_back(temp);
fill_Array(num/=10);
}
}
int main()
{
int n;
cin>>n;
fill_Array(n);
for(int i=0; i<arr.size(); i++)
{
cout<<arr[i]<<endl;
}
return 0;
}
A couple of reasons I can see:
There is no conditional to stop the recusion so it will keep going until it runs out of stack or memory. I presume you want to stop when num is zero
fill_Array has no return value so will assign temp with some random value which will be pushed into the array
Also why use recursion for this when iterative would be easier and more obvious what it is doing

How to fill a vector of struct

I have the following code, where i defined a vector of vector of struct
#include <vector>
#include <iostream>
using namespace std;
struct node
{
int index;
double value;
};
int main()
{
vector < vector <node> >vett1;
node p;
p.index=5;
p.value=2;
for (int i=0; i<10; i++)
vett1[i].push_back(p);
return 0;
}
i don't know the right way to fill it. In this way when i run it, compilers gives me segmentation fault error.
When you access vett1[i], but the vett1 has not been filled with size zero. That's why the segmentation fault error occur.
Three ways to fix it:
Add
vett1.resize(10);
before the for loop.
Or define vett1 and set its size as follows:
vector <vector <node>> vett1(10);
Or you can do this if you don't know the exact size pre-hand:
for (int i=0; i<10; i++)
{
vector<node> temp;
temp.push_back(p);
vett1.push_back(temp);
}

Graham scan c++ won't work

My code for the graham scan is not working, it is supposed to get the perimeter of the convex hull. It gets the input of n points, which can have decimals. The algorithm returns a value higher than the actual perimeter.
I am using what I understood from:
http://en.wikipedia.org/wiki/Graham_scan
#include <iostream>
#include <cstdio>
#include <cmath>
#include <vector>
#include <algorithm>
using namespace std;
#define PI 3.14159265
int nodes;
double xmin=10000000, ymin=10000000, totes=0;
struct ppoint
{
double x, y, angle;
void anglemake()
{
angle=atan2(y-ymin, x-xmin)*180/PI;
if(angle<0)
{
angle=360+angle;
}
}
} np;
The point structure, with a function to make the angle between it and the point with lowest y and x coordinates
vector<ppoint> ch, clist;
bool hp(ppoint i, ppoint j)
{
return i.angle<j.angle;
}
double cp(ppoint a, ppoint b, ppoint c)
{
return ((b.x-a.x)*(c.y-a.y))-((b.y-a.y)*(c.x-a.x));
}
The z-cross product function
double dist(ppoint i, ppoint j)
{double vd, hd;
vd=(i.y-j.y)*(i.y-j.y);
hd=(i.x-j.x)*(i.x-j.x);
return sqrt(vd+hd);
}
Distance generator
int main()
{
scanf("%d", &nodes);
for(int i=0; i<nodes; i++)
{
scanf("%lf%lf", &np.x, &np.y);
if(np.y<ymin || (np.y==ymin && np.x<xmin))
{
ymin=np.y;
xmin=np.x;
}
ch.push_back(np);
}
Gets the points
for(int i=0; i<nodes; i++)
{
ch[i].anglemake();
}
sort(ch.begin(), ch.end(), hp);
clist.push_back(ch[0]);
clist.push_back(ch[1]);
ch.push_back(ch[0]);
Sorts and starts Graham Scan
for(int i=2; i<=nodes; i++)
{
while(cp(clist[clist.size()-2], clist[clist.size()-1], ch[i])<0)
{
clist.pop_back();
}
clist.push_back(ch[i]);
}
Graham scan
for(int i=0; i<nodes; i++)
{
totes+=dist(clist[i], clist[i+1]);
}
Gets length of the perimeter
printf("%.2lf\n", totes);
return 0;
}
Just for the interest, print out value of nodes and clist.size() before the dist summming.
At glance clist can have nodes+1 items only if pop_back never happens. and if it does you have undefined behavior.
I think the problem is here:
for(int i=0; i<nodes; i++)
{
totes+=dist(clist[i], clist[i+1]);
}
clist will only have the remaining number of points, not nodes + 1 which is the number of points you loaded plus one. Storing this number in the first place is a fault IMHO, because it starts with the number of points, then you add one to close the loop, then again you remove points to make the hull convex. Just use container.size() and everything is clear.
One more note: Use a checked C++ standard library implementation for debugging. These would have warned you of undefined behaviour like accessing a vector beyond its range. C++ is a language that allows you to shoot yourself in the foot in to many ways, all in the name of performance. This is nice and well, unless when debugging, which is when you want the best diagnostics available.

C++ Vector Elements Count

In C++, using the vector header, how do I find the number of elements?
#include <iostream>
#include <cmath>
#include <fstream>
#include <cstdlib>
#include <vector>
using namespace std;
int primer(int max);
int main()
{
system("pause");
return 0;
primer(1000);
}
int primer(int max){
vector<int> a;
a[1]=2;
for (int i=2;i<=max;i++){
bool prime=true;
for (int ii=1;ii<=#a;ii++) {
if i/a[ii]==math.floor(i/a[ii]) {
prime=false;
}
}
if prime==true {
a[#a+1]=i;
}
}
for (i=1;i<=#a;i++) {
cout << a[i]);
}
}
}
I originally wrote the code
for lua, and this is my attempt to translate it to C++. I would appreciate specifics, for example, a specific replacement for a bad line. I tried to replace #a with a.size, but it didn't work.
Revised:
#include <iostream>
#include <cmath>
#include <fstream>
#include <cstdlib>
#include <vector>
using namespace std;
int primer(int max);
int main()
{
primer(5);
system("pause");
return 0;
}
int primer(int max){
vector<int> a;
a[1]=2;
for (int i=2;i<=max;i++){
bool prime=true;
for (int ii=0;ii<a.size();ii++) {
if (i/a[ii]==floor(i/a[ii])) {
prime=false;
}
}
if (prime==true) {
a.push_back(i);
}
}
for (int iii=0;iii<=a.size();iii++) {
cout << a[iii] << endl;
}
}
It crashes without running. For what reason is this?
a.size().
I would recommend using some sort of reference material, e.g. http://cplusplus.com/reference/stl/vector/.
To answer your immediate question:
a.size(); // use size as a function
But there are several other things wrong with your code:
vector<int> a;
a[1]=2;
Ordinarily you need to set the size of a beforehand, since C++ must allocate space for it. You can use push_back() though, which will incrementally add space as needed.
Also, C++ arrays start counting at 0:
for (int ii=1;ii<=#a;ii++) {
This should be
ii = 0
And since arrays start at 0, they end at size() - 1, not size().
for( int ii = 0; ii < a.size(); ++ii )
C and C++ array indexes start at zero and end at size-1, so you need to compare less-than, not less-than-or-equal-to. vector follows the same rule.
Another obvious problem that needs pointing out:
int main()
{
system("pause");
return 0;
primer(1000);
}
Your function is never going to be called. Your app will exit when main returns.
a[#a+1]=i;
changed to use size() becomes:
a[ a.size() + 1 ] = i;
This is syntactically correct but guaranteed wrong. It should be:
a.push_back(i);
Read the API referenced by Oli.