模板程序不断崩溃

时间:2011-06-10 03:06:51

标签: c++ crash

我的程序将编译并运行正常,但是当程序中的im时它会崩溃。 知道为什么吗?

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++;
    }
}

2 个答案:

答案 0 :(得分:1)

有几个问题。但是导致崩溃的问题是,

for (int i = 0; i < maxSize; i++)

想象一下,如果您输入的maxSize大于arrSize,该怎么办?缓冲区将溢出,导致未定义行为或崩溃。同样适用于填充while数组的double循环。

在旁注中,将findFeq的签名更改为:

template<class T>
T findFeq (T arr1[], T target, unsigned int arrSize); // arrSize must be of integer type

答案 1 :(得分:0)

问题:

  • maxSize可能大于SIZE - &gt; 数组越界

  • T findFeq(T arr1 [],T target, size_t arrSize); - &GT; 数组大小不应该依赖于类型T

  • fillDoubleArray(dArray,大小,的 dspacesUsed ); - &GT;这很危险,第3个参数sdpacesUsed 应该是int&amp;不是双倍&amp; 。这不应该通过编译。