getting heap corruption and program crashing - c++

I have written following to solve following problem
"Given a list of unsorted numbers, can you find the numbers that have the smallest absolute difference between them? If there are multiple pairs, find them all."
Here is code
#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <cstdlib>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
using namespace std;
int* smallestDiff(vector<int> a,int &noOfPairs)
{
sort(a.begin(),a.end());
int * arr = new int(a.size()* sizeof(int) *2);
bool bfoundDiff = false;
int smallestDiff =0;
int num1,num2;
for(size_t i=0;i<a.size()-1;i++)
{
num1 = a[i];
num2 = a[i+1];
int newDiff = num2-num1;
if(!bfoundDiff || newDiff < smallestDiff)
{
smallestDiff = newDiff;
arr[0] = num1;
arr[1]= num2;
noOfPairs = 1;
bfoundDiff = true;
}
}
for(size_t i=0;i<a.size()-1;i++)
{
num1 = a[i];
num2 = a[i+1];
int newDiff = num2-num1;
if(newDiff == smallestDiff && num1!=arr[0] && num2!=arr[1])
{
arr[noOfPairs*2] = num1;
arr[noOfPairs*2 + 1] = num2;
++noOfPairs;
}
}
return arr;
}
int main() {
int _a_size;
cin >> _a_size;
cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
vector<int> _a;
int _a_item;
for(int _a_i=0; _a_i<_a_size; _a_i++) {
cin >> _a_item;
_a.push_back(_a_item);
}
int noOfPairs=0;
int *result =smallestDiff(_a,noOfPairs);
int noOfelems = noOfPairs*2;
for(int i=0;i<noOfelems;++i)
{
cout<< *(result+i)<<" ";
}
return 0;
}
Now program is running fine as per logic but its crashing when it tries to print result values.I dont see anything wrong with passing pointer as return type.
Do you guys see any issue here?

You've made a typo in the following line:
int * arr = new int(a.size()* sizeof(int) *2);
It should be like this:
int * arr = new int[a.size()* sizeof(int) *2];
Instead of allocating an array you allocate single integer and initialize it with what you think had to be size.

Related

std::cin string to int array with variable length input

I have a task where i need to revert a list of variable length numbers. This could be "1 2 3" or "5 6 7 8 9 10".
The sorting itself works fine.
But I can't figure out how to read the user input (with variable length) and then only execute the reverseSort once.
How can I read the user input into an array where each index is based on the space between the numbers?
Here is my code:
#include <iostream>
#include <string>
using namespace std;
bool sorted = true;
int temp;
int * arr;
int arrLength = 5;
int arrs;
// int arr = {1,2,3,4,5};
void reverseSort(int arr[], int n){
sorted = true;
for (int i = 0; i < n-1; i++){
if (arr[(i + 1)] > arr[i]){
temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
sorted = false;
}
}
if (!sorted){
reverseSort(arr,n);
}
}
int main(void){
// get user input !?!?!?!?!
cin >> arrs;
cout << arrs;
reverseSort(arr,arrLength);
for (int i = 0; i < arrLength; i++){
std::cout << arr[i] << " ";
}
return 0;
}
If you don't know number of inputs you need struct that can be resized. std::vector is good for it. For adding new data you can use member function push_back.
You can read the input line as std::string (by std::getline) and you can open new stream with read data (std::istringstream). Further one can read values from new stream.
And I think you can use std::sort instead of reverseSort (but for 'reverse' you need use std::greater as comparator).
#include <vector>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <algorithm>
int main(void){
std::vector<int> arrs;
// read only one line
std::string input;
std::getline(std::cin, input);
std::istringstream row(input);
int x;
while (row >> x)
{
arrs.push_back(x);
}
//like your reverseSort
std::sort(arrs.begin(), arrs.end(), std::greater<int>{});
for (auto var : arrs) {
std::cout << var << "; ";
}
return 0;
}

How to insert the range of numbers to an array by iterating through it?

I am making a program, in which I need to iterate the numbers, starting from 1 to num then put the value of that array {1...num} to a variable that can be called in the for loop.
This is where I am at.
int main()
{
int num = 0;
cin >> num;
for (int i = 1; i <= num; i++)
{
procnum[i];
}
}
I need procnum[num] to have a value like ...
int procnum[num] = {1,2,3...num};
If you can use std::vector and std::iota, this is just two line code.
No need to for(index) loop the array. See live example here
#include <vector> // std::vector
#include <numeric> // std::iota
std::vector<int> procnum(some_size);
std::iota(procnum.begin(), procnum.end(), 1);
In C++11, no need to even write a loop, unless you need to do error checking (e.g. check that reading input succeeded, or that the input value is valid).
#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>
int main()
{
int size;
std::cin >> size;
std::vector<int> procnum(size);
std::iota(procnum.begin(), procnum.end(), 1); // starting value is 1
// output vector to demonstrate it is populated
std::copy(procnum.begin(), procnum.end(), std::ostream_iterator<int>(std::cout," ");
std::cout << "\n";
}
Before C++11, there was no algorithm std::iota(), but it is possible to use std::generate() and a simple functor to achieve the same effect.
you can use std::vector to create dynamic arrays:
#include <iostream>
#include <vector>
int main() {
int size;
std::cin >> size;
std::vector<int> procnum(size);
for (int i = 0; i < size; ++i) {
procnum[i] = i + 1;
}
}
you shouldn't use namespace std; - read here why.

how is this cpp code running without a main function?

topcoder problem BearNSWE submitted by zig_zag
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <cmath>
#include <ctime>
#include <vector>
#include <cstdio>
#include <string>
#include <climits>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
double xx, yy;
class BearNSWE
{
public:
double totalDistance(vector <int> a, string dir)//no main function
{
int n = a.size();
double ans = 0.0;
xx = yy = 0.0;
for (int i = 0; i < n; i++)
{
if (dir[i] == 'N')
{
yy = yy + a[i];
}
else if (dir[i] == 'S')
{
yy = yy - a[i];
}
else if (dir[i] == 'W')
{
xx = xx - a[i];
}
else if (dir[i] == 'E')
{
xx = xx + a[i];
}
ans = ans + a[i];
}
return ans + sqrt(xx*xx + yy*yy);
}
};
The topcoder runner expects a class with a specific method interface, it is specified in the problem statement. For this specific problem, it is here.
Topcoder will compile this code with additional sources - a main method, which runs the examples - added.
If you want to test your code locally in the topcoder editor (or just autogenerate the code for running it), there are several plugins available for it, for example the ExampleBuilder.
That is just a .cpp file with a class definition. The main() function is located somewhere else in the project.

Segmentation fault in c++ code unable to find reason

I am getting segmentation for the last test case (Don't know what it is ) while solving the problem GREATESC.
Concept of the problem is basic bfs. Given an undirected graph |V| <= 3500 and |E| <= 1000000
Find the minimum distance between two given vertices.
Here's the problem link http://opc.iarcs.org.in/index.php/problems/GREATESC
Here's my solution link
http://ideone.com/GqTc6k
#include <iostream>
#include <stdio.h>
#include <cmath>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <cassert>
#include <ctime>
#include <cstdlib>
#include <algorithm>
#define Pi 3.14159
#define vi vector<int>
#define pi pair<int,int>
#define si stack<int>
typedef long long int ll;
using namespace std;
bool b[3501][3501]={0};
int main ()
{
int n,m;
cin >>n>>m;
int u,v;
for (int i =1;i<= m;i++)
{
scanf("%d",&u);
scanf("%d",&v);
b[u][v]=b[v][u]=1;
}
// input completed.
int dist[n+1];
int h,V;
cin >>h>>V;
dist[h]=0;
//cout<<"hero "<<h<<" "<<V<<endl;
queue<int> q;
bool bfs[3501];
for (int i=1;i<= n;i++)bfs[i]=1;
q.push(h);
bfs[h]=0;
while (!q.empty())
{
int top = q.front();
// cout<<top<<endl;
q.pop();
for (int i = 1 ;i <= 3500;i++)
{
if(bfs[i] && b[i][top])
{
int x = i;
dist[i] = dist[top] +1;
if(x == V){cout<<dist[x]<<endl;return 0;}
bfs[x]=0;
q.push(x);
}
}
}
cout<<0<<endl;
}
You have this:
cin >>n>>m;
...
int dist[n+1];
Hence the array dist may have size less than 3500. But:
for (int i = 1 ;i <= 3500;i++)
...
dist[i] = dist[top] +1;
This code might be indexing outside of dist.
You seem to need in general to be more careful that when indexing into an array, you're inside the bounds of the array.
Consider using std::vector instead of arrays, then indexing with at to get bounds checking. Or alternatively, manually assert that values are within range:
#include <assert.h>
...
for (int i = 1 ;i <= 3500;i++)
...
assert(i >= 0 && i <= n && top >= 0 && top <= n);
dist[i] = dist[top] +1;

garbage value is obtained

this is a sample of my code. i am getting the value for maximum height. but my minimum height is a garbage value. what am i doing wrong
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <sstream>
using namespace std;
#define MAX 20
struct DATA
{
int id;
string name;
float height;
}numarray[MAX];
int main()
{
int num = 0;
numarray[num].height = fstr3;// contains float values from a file
float minimum, maximum;
minimum = numarray[0].height;
maximum = numarray[0].height;
for(int i = 0; i < MAX; i++)
{
{
if(numarray[i].height < minimum)
{
minimum = numarray[i].height;
}
else if(numarray[i].height > maximum)
{
maximum = numarray[i].height;
}
}
cout<< minimum<< " " << maximum<< endl;
return 0;
}
}
Garbage in, garbage out. It looks like your input routine (which you didn't post) may be populating the data incorrectly. I'd look at the input data in the debugger (even if your choice of debugger is printf()).
Your code assumes that minimum is unequal to the maximum.
Solution second if should be on its own and not in else clause from first.
assuming you do initialize the array in your real code, with these modifications:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <sstream>
using namespace std;
#define MAX 20
struct DATA
{
int id;
string name;
float height;
}numarray[MAX];
int main()
{
int num = 0;
numarray[num].height = fstr3;// contains float values from a file
float minimum, maximum;
minimum = numarray[0].height;
maximum = numarray[0].height;
for(int i = 1 /* skip 0 - already read */; i < MAX; i++)
{
if(numarray[i].height < minimum)
{
minimum = numarray[i].height;
}
// remove the else here
if(numarray[i].height > maximum)
{
maximum = numarray[i].height;
}
}
// move outside the loop
cout<< minimum<< " " << maximum<< endl;
return 0;
}
this should be OK