My program will compile and run fine but it crashes when im in the program.
Any idea why?
template<class T>
T findFeq (T arr1[], T target, T arrSize);
template<class T>
T findFreq (T arr1[], T target, T arrSize){
int count = 0;
for(int i = 0; i < arrSize; i++){
if (target == arr1[i])
count++;
}
return count;
}
#include "Ex1.h"
#include <iostream>
using namespace std;
void fillIntArray(int arr1[], int arrSize, int& spacesUsed);
void fillDoubleArray(double arr1[], int arrSize, int& spacesUsed);
int main(){
const int SIZE = 1000;
int itarget = 42;
double dTarget = 42.0;
int ispacesUsed;
double dspacesUsed;
int iArray[SIZE];
double dArray[SIZE];
fillIntArray(iArray,SIZE,ispacesUsed);
cout << findFreq(iArray,itarget,ispacesUsed) << endl;
fillDoubleArray(dArray,SIZE,dspacesUsed);
cout << findFreq(dArray,dTarget,dspacesUsed) << endl;
return 0;
}
void fillIntArray(int arr1[], int arrSize, int& spacesUsed){
int maxSize;
cout << "How many numbers shall i put into the Array? ";
cin >> maxSize;
for (int i = 0; i < maxSize; i++){
arr1[i] = (rand()% 100);
spacesUsed++;
}
}
void fillDoubleArray(double arr1[], int arrSize, int& spacesUsed){
int maxSize,i = 0;
cout << "How many numbers shall i put into the Array? ";
cin >> maxSize;
while (i < maxSize){
cout << "Enter number to put in Array: ";
cin >> arr1[i];
i++;
}
}
There are several problems. But the problem which will cause a crash is,
Just imagine what if you enter
maxSizegreater thanarrSize? The buffer will overflow and it causes either an Undefined behavior or crash. Same is applicable forwhileloop meant for fillingdoublearray.On the side note, change the signature for
findFeqto: