For an assignment I have to make this little thing that displays crude histograms. i'm getting this error, and I can't figure out what's wrong, help would be greatly appreciated.
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
#include <iostream>
usingnamespace std;
// read data from console
void getData (int size, int *Arr){
cout << "\n\nEnter integer data one line at a time\n" << endl ;
for (int i=0; i < size; i++){
cin >> Arr[i];
}
}
int* makeFrequency (int *data, int dSize, int *minDataValue, int *maxDataValue){
*minDataValue = data[0];
*maxDataValue = data[0];
int i = 0;
while (i < dSize) {
if (*minDataValue < data[i]){
*minDataValue = data[i];
}
if (*maxDataValue > data[i]){
*maxDataValue = data[i];
}
i++;
}
int difference = (*maxDataValue - *minDataValue)+1;
int *freqArray;
freqArray = newint[difference];
int k = 0;
while (k < difference){
freqArray[k] = 0;
k++;
}
int j = 0;
while (j < difference) {
int temp = data[j] - *minDataValue;
freqArray[temp] += 1;
j++;
}
return freqArray;
}
// make histogram from the frequency array
void makeHistogram ( int *freq, int min, int max ){
cout << "\n\n\n ----------- Histogram ----------------\n" << endl;
int size = max - min + 1;
for (int i = 0; i < size; i++){
if (freq[i] > 0){
cout << "\n" << min + i << ": ";
for (int j = 0; j < freq[i]; j++) {
cout << '*';
}
}
}
cout << endl << endl;
}
int main() {
int dSize;
int *ArrayOfInts;
cout << "How many data values? ";
cin >> dSize;
ArrayOfInts = newint [dSize];
getData (dSize, ArrayOfInts);
int *frequency;
int min,max;
frequency = makeFrequency(ArrayOfInts, dSize, &min, &max);
if (frequency == NULL) return -1;
makeHistogram (frequency, min, max);
return 0;
}
Have you tried stepping through the code in a debugger to find the bad memory allocation? Its probably line 34, and it might be that you got your variable allocations the wrong way round, and you are now ending up with attempting to allocate a negative sized block of memory. Also, on line 90, frequency will never equal nullptr (NULL), because new throws on failure unless you specify the nothrow variant.
EDIT:
Yes, you have your comparison operators the wrong way round in lines 22 and 25.