Getting Bad_alloc thrown when running this code - c++

I am getting a bad_alloc thrown when I run the executable generated from this code. I do not know why it's being thrown (I can guess it's coming from that new statement)
#include <iostream>
#include <chrono>
#include <cmath>
using namespace std;
void gen_numbers(long int numbers[], long int how_many)
{
for (int i = 0; i < how_many; i++)
{
numbers[i] = i;
}
}
bool is_prime(long int n)
{
if(n < 2)
return false;
for(int i=2; i<=sqrt(n); i++)
{
if(n % i == 0)
return false;
}
return true;
}
int count_prime_serial(long int numbers[], long int how_many)
{
int count = 0;
for(int i=0; i<how_many; i++)
{
if(is_prime(numbers[i]))
count++;
}
return count;
}
int main(){
long int n = 1000000000;
long int* numbers = new long int[n];
gen_numbers(numbers, n);
auto start = chrono::steady_clock::now();
int count = count_prime_serial(numbers, n);
auto end = chrono::steady_clock::now();
double compute_time = chrono::duration<double>(end - start).count();
cout<<"Total number of primes = "<<count<<endl;
cout<<"Total computation time = "<<compute_time<<endl;
return 0;
}
Is there any solution to stop getting this error during runtime?
I've tried compiling and running the exact same code on another machine and it ran just fine, this is why I am confused.

Related

Weird crashing program while debug runs smoothly (Eclipse C++)

I'm writing a program for my algorithmic math class at university and I'm using Win 7 (x64), Eclipse Oxygen.1a Release (4.7.1a) with MinGW 6.3.0.
Whenever I build and run the program it crashes with windows claiming 'Abgabe3.exe stopped working' but when trying to find the problem using the debugger and breakpoints I step trough the whole program and it finishes without errors...
I stripped everything not used by the problematic function and copied everything into a seperate file and the exact problem occurs.
Maybe somebody has a clue what happened at my side. ^^
#include <math.h> /* pow, sqrt */
#include <iostream> /* cin, cout */
#include <new> /* new */
#include <string> /* string */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
using namespace std;
void NORM(double* res, double* x, int n){
res[0] = 0.0;
for(int i = 0; i < n; i++){
res[0] += pow(x[i], 2);
}
res[0] = sqrt(res[0]);
}
void initRand(double* x, int n){
srand (time(NULL) * rand());
for(int i = 0; i < n; i++){
x[i] = (((double) rand()) / ((double) RAND_MAX));
}
}
void createArray(double* &x, int n){
if (n > 0){
x = new double[n];
initRand(x, n);
}
}
void printArray(double* x, int n){
if (x != NULL){
cout<<"(\n";
for(int i = 0; i < n; i++){
if(i+1 == n) cout<<x[i];
else if ((i % 5) == 0) cout<<x[i];
else if ( ((i+1) % 5) == 0 ){
cout<<", "<<x[i]<<"\n";
}
else {
cout<<", "<<x[i];
}
}
cout<<"\n)\n";
}
else cout<<"\nError: pointer = NULL\n";
}
unsigned long long int bin(unsigned int n, unsigned int k){
unsigned long long res = 1;
if(k == 0) return 1;
else if( n >= k){
for(unsigned long long int i = 1; i <= k; i++){
res *= (n + 1 - i) / i;
}
}
else return 0;
return res;
}
void newArray(double** x, unsigned int v, unsigned int n){
for(unsigned int i = 0; i < v; i++){
double* ptr = x[i];
createArray(ptr,n);
x[i] = ptr;
}
}
void experiment(double** vektorArray){
unsigned int n = 10, v = 20;
cout<<"Dimension n = "<<n<<"\nAnzahl Versuche v = "<<v<<endl;
//Erstellen der Vektoren
cout<<"Erstellen - starte\n";
vektorArray = new double*[n];
newArray(vektorArray, v, n);
cout<<"Erstellen - fertig\n";
for(unsigned int i = 0; i < v; i++){
if(i%10 == 0) printArray(vektorArray[i], n);
}
}
int main(int argc, char** argv){
double** vektorArray = NULL;
experiment(vektorArray);
return 0;
}
vektorArray = new double*[n];
created an array of size n, but
void newArray(double** x, unsigned int v, unsigned int n)
{
for (unsigned int i = 0; i < v; i++)
{
double* ptr = x[i];
createArray(ptr, n);
x[i] = ptr;
}
}
and
for (unsigned int i = 0; i < v; i++)
{
if (i % 10 == 0)
printArray(vektorArray[i], n);
}
index that array with v. Looks like you got your variables crossed. Strongly recommend giving variables better, more descriptive names to help make this more obvious.

C++ Program loops forever

I seem to be having an issue that I've been stuck on for hours. I run the program, and it just hangs after asking for the user input. My computer also begins to slow down unless I terminate the program. I have no idea what the problem is. I have tried commenting out code to see where the issue may be coming from. I put a cout statement after asking for the input, and even that does not display.
#include <iostream>
#include <vector>
#include <stdexcept>
#include <iomanip>
#include <cstdlib>
#include <array>
#include "problem2.h"
using namespace std;
int binarySearch(int array[], int input);
void selectSort(int arr[], int n);
int problem2() {
srand(time(0)); // generate seed based on current system time
int rand[20];
int result;
int input = 1;
cout << "Enter a number to search for: ";
cin >> input;
cout << "testset ";
for (int z = 0; z < 19; z++) {
rand[z] = random() % 70;
cout << rand[15];
}
selectSort(rand, 20);
for (int t = 0; t < 20; t++) {
//cout << random1D[z];
}
result = binarySearch(rand, input);
//cout << result;
return 0;
}
int binarySearch(int arr[], int a) {
int high = 19;
int middle = 19/2;
int low = 0;
while (arr[middle] != a && low<= high) {
if (arr[middle] > a) {
high = middle - 1;
} else {
low = middle - 1;
}
if (low > high) {
}
}
return middle;
}
void selectSort(int arr[], int n) {
int min, temp;
for (int i = 0; i < n-1; i++) {
min = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[min])
min = j;
}
if (min != i) {
temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
}
}
You have several loops, but all of them except for one have explicit termination. The for loops all end after a specific number of iterations, but your while loop is less certain. Your low is likely never going to be greater than your high, so the loop just keeps going.
Consider changing to low = middle + 1 or altering your logic to more likely ensure that low will eventually overtake high. Or, change the condition the while loop checks.

Runtime error in code (C++)

i am a beginner to c++ but i wouldn't have asked this question if i didnt spend hours on it.
The code is about finding primes between two numbers in the most efficient way where maximum limit is 10^9.
The following code gives me runtime error but i have no idea why.. help
#include <iostream>
#include <stdio.h>
#include <math.h>
using namespace std;
long int prime[32000];
bool isprime(long int a){
for(long int i = 3; i <= 32000; i+=2){
if(a%i == 0){
return false;
}
}
return true;
}
void generateprimes(){
long int a = 0;
for(long int i = 3; i < 31623 ; i+=2){
if(isprime(i)){
prime[a] = i;
a++;
}
}
}
bool newisprime(long int a){
long int x =0;
for(long int i = prime[x]; i <= sqrt(a); i = prime[++x]){
if(a%i == 0){
return false;
}
}
return true;
}
void generateprimes_inbetween(long int n,long int m){
if(n%2 == 0){
++n;
}
if(n == 1){
printf("2\n");
n = 3;
}
for(long int i = n; i <= m ; i+=2){
if(newisprime(i)){
printf("%d\n",i);
}
}
}
int main() {
long int a,b,c;
scanf("%ld",&a);
generateprimes();
for(long int i = 0; i < a ; i++){
scanf("%ld %ld",&b,&c);
generateprimes_inbetween(b,c);
printf("\n");
}
return 0;
}
In isprime() you loop through ALL numbers in your array prime[]. But at startup, as it's global data, most of them will be 0, so that a%i will result in a fatal divide by 0.
You have somewhere to keep track of the numer of primes that you've stored in your array and only test against the primes that you've stored there.
Supposing that it's homework and you're not allowed to use vectors, you could do it as follows:
const size_t max_primes = 32000; // avoid hard coded values
unsigned long prime[max_primes] {2, 3}; // prefilled values
size_t nprimes = 2; // number of primes in the array
bool isprime(unsigned long a){
for(size_t i = 0; i < nprimes; i++){
if(a%prime[i] == 0)
return false;
}
return true;
}
void generateprimes(){
nprimes = 2;
for(unsigned long i = 3; nprimes<max_primes && i < ULONG_MAX; i += 2){
if(isprime(i)){
prime[nprimes] = i;
nprimes++;
}
}
}
bool newisprime(unsigned long a){
size_t x = 0;
for(unsigned long i = prime[x]; i <= sqrt(a) && x<nprimes; i = prime[++x]){
if(a%i == 0)
return false;
}
if(x == nprimes) {
cout << "Attention: Reaching end of prime table !!" << endl;
}
return true;
}
Some remarks:
for the index, it's safer to use the unsigned type size_t.
make sure that whenever you use an index, it remains within the bounds
as you work with positive numbers, it could make sense to use unsigned long

wrong output with large test case in union find

I wrote a simple union find implementation using quick find method. Here is my code
#include <iostream>
using namespace std;
class QuickFind
{
int* id;
int size;
public:
QuickFind(int n)
{
id = new int[n];
size = n;
for(int i = 0; i < size; i++) id[i] = i;
}
bool is_connected(int p, int q)
{
return id[p] == id[q];
}
void do_union(int p, int q)
{
int tempP = p;
int tempQ = q;
for(int i = 0; i < size; i++)
{
if(id[i] == tempP) id[i] = tempQ;
}
}
};
int main()
{
QuickFind obj(10000);
obj.do_union(5,6);
obj.do_union(6,8);
cout<<obj.is_connected(5,6)<<endl;
for(int i = 0; i < 1000; i++)cout<<obj.is_connected(i,i+1)<<endl;
return 0;
}
I also wrote a for loop in main. This prints correct answers when I loop it say 50 or 100 times. But it is giving me all 0s when i loop it like 1000 or more times. I'm using codeblocks ide.
Also when i compiled the same code in codechef's online compiler i get correct output. Can anyone tell me about this anomaly?

Passing an array as a parameter to a function

So I'm doing a programming assignment and I've ran into an issue, when every I attempt to pass the arrays to the header file, I receive an error while compiling, I'm not too clear as how to do this and would much appreciate so assistance in passing these arrays.
Here is the Header file "sorting.h"
#include <iostream>
#include <cstdlib>
using namespace std;
int cost = 0;
void bubble(int Ar[],int N)
{
cost=0;
int swaps = 1;
while(swaps)
{
swaps=0;
for(int i = 0;i<N;i++)
{
if(Ar[i]>Ar[i++])
{
swap(Ar[i],Ar[i++]);
swaps = 1;
cost += 6;
}
cost++;
}
}
for(int i=0;i<N;i++)
{
cout<<Ar[i]<<endl;
}
cout<<cost<<endl;
}
void shellSort(int Ar[], int N)
{
cost=0;
int swaps = 1;
int gap = N/2;
while(gap>0)
{
while(swaps)
{
swaps = 0;
for(int i = 0;i<N;i++)
{
if(Ar[i]>Ar[i+gap])
{
swap(Ar[i],Ar[i+gap]);
swaps = 1;
cost+=6;
}
cost++;
}
}
gap=gap/2;
}
for(int i = 0;i<N;i++)
{
cout<<Ar[i]<<endl;
}
cout<<cost<<endl;
}
void quickSort(int Ar[],int left, int right, int N)
{
cost = 0;
int i=left,j=right,tmp;
int pivot = Ar[(left+right)/2];
/*partition*/
while(i<=j)
{
while(Ar[i]<pivot)i++;
while(Ar[j]>pivot)j--;
if(i<=j)
{
tmp=Ar[i];
Ar[i]=Ar[j];
Ar[j]=tmp;
i++;
j--;
cost +=6;
}
cost+=1;
}
/* recursion*/
if(left<j)quickSort(Ar,left,j,N);
if(i<right)quickSort(Ar,i,right,N);
for(int i=0;i<N;i++)
{
cout<<Ar[i]<<endl;
}
cout<<cost<<endl;
}
/*#if _INCLUDE_LEVEL__<1
int main()
{
}
#endif*/
and here is the main file "sorting2.cpp"
#include <iostream>
#include <cstdlib>
#include "sorting.h"
using namespace std;
//void bubble();
//void shellSort();
//void quickSort();
int main()
{
int N = 20;
int Ar[N];
int Ar2[N];
for(int i = 0;i<N;i++)
{
Ar[i] = Ar2[i] = rand()%100;
}
bubble(Ar[],N);
for(int i = 0;i<N;i++)
{
Ar[i] = Ar2[i];
}
shellSort(Ar[],N);
for(int i = 0;i<N;i++)
{
Ar[i] = Ar2[i];
}
quickSort(Ar[],0,19,N);
}
Thanks in advance!
Change
bubble(Ar[],N);
to
bubble(Ar, N);
(and in other similar places as well)
There are also other problems in your code:
Variable-length arrays are not part of C++ standard:
int Ar[N];
int Ar2[N];
You should change int N = 20; to const int N = 20;
This line produces undefined behavior because the order of evaluation of operator arguments is unspecified:
if(Ar[i]>Ar[i++])