Search code examples
c++linuxg++bad-alloc

std::bad_alloc when declaring new int[n]


The program is supposed to take an array from user-input and split it into two arrays for negative and non-negative values respectively.

The program works up to and including

count(userList, n, numPos, numNeg); 

The error throws when I declare

int *negList = new int[numNeg];
int *posList = new int[numPos];

I thought that changing it to

int *negList;
negList = new int[numNeg];
int *posList;
posList = new int[numPos];

would fix the problem, but it does not. The previous declaration of

int *userList;
userList = new int[n];

does not throw any error.

This happens both in Codeblocks on windows as well as on Linux with g++.

The whole code is below:

#include <iostream>

using namespace std;

//count positive and negative elements in list
void count(const int* arr/*list*/, int numElements/*num elements in array*/, int& numPos/*num positive elements*/, int& numNeg/*num negative elements*/);

int main()
{
  //declare variables
  int n;                  //number of elements
  int userInput;          //place holder for list values
  int numPos; int numNeg; //num positive and negative elements

  //prompt user for number of elements
  cout << "Enter number of elements: ";
  cin >> n;

  //declare array
  int *userList;
  userList = new int[n];

  //prompt user for list and read in
  cout << "Enter list: " << endl;
  cin >> userInput;
  for(int i(0); i < n; i++){
    cin >> userInput;
  }

  //count positive and negative elements
  count(userList, n, numPos, numNeg);

  //declare arrays for negative and positive elements respectively
  int *negList = new int[numNeg];
  int *posList = new int[numPos];

  // ...

  //free memory
  delete [] userList;
  delete [] negList;
  delete [] posList;

  return 0;
}

void count(const int* arr, int numElements, int& numPos, int& numNeg)
{
  for(int i(0); i < numElements; i++){
    if(arr[i] < 0){
      numNeg++;
    }
    else{
      numPos++;
    }
  }
}

All help is greatly appreciated!


Solution

  • You need to initialize numNeg and numPos to 0.