问题描述
|
我的程序可以编译并正常运行,但是当我在程序中时崩溃。
知道为什么吗?
template<class T>
T findFeq (T arr1[],T target,T arrSize);
template<class T>
T findFreq (T arr1[],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& 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,dspacesUsed);
cout << findFreq(dArray,dTarget,dspacesUsed) << endl;
return 0;
}
void fillIntArray(int arr1[],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& 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++;
}
}
解决方法
有几个问题。但是会导致崩溃的问题是
for (int i = 0; i < maxSize; i++)
试想一下,如果输入的maxSize
大于arrSize
会怎样?缓冲区将溢出,并导致未定义行为或崩溃。同样适用于用于填充double
数组的while
循环。
在旁注中,将“ 6”的签名更改为:
template<class T>
T findFeq (T arr1[],T target,unsigned int arrSize); // arrSize must be of integer type
, 问题:
maxSize
可以大于SIZE
->数组超出范围
T findFeq(T arr1 [],T target,size_t arrSize); ->数组大小不应取决于类型T
fillDoubleArray(dArray,SIZE,dspacesUsed); ->这很危险,第三个参数sdpacesUsed
应该是int&而不是double&。这不应该通过编译。