简体   繁体   English

模板程序不断崩溃

[英]Template program keeps crashing

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,但是会导致崩溃的问题是,

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

Just imagine what if you enter maxSize greater than arrSize ?想象一下,如果您输入的maxSize大于arrSize怎样? The buffer will overflow and it causes either an Undefined behavior or crash .缓冲区将溢出并导致未定义行为或崩溃 Same is applicable for while loop meant for filling double array.同样适用于用于填充double数组的while循环。

On the side note, change the signature for findFeq to:在旁注中,将findFeq的签名更改为:

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

Problems:问题:

  • maxSize can be greater than SIZE --> array out of bounds maxSize可以大于SIZE -->数组越界

  • T findFeq (T arr1[], T target, size_t arrSize); T findFeq(T arr1[], T target, size_t arrSize); --> array size should not depend on type T -->数组大小不应该依赖于类型 T

  • fillDoubleArray(dArray,SIZE, dspacesUsed ); fillDoubleArray(dArray,SIZE, dspacesUsed ); --> this is dangerous, the 3rd argument sdpacesUsed should be int& not double& . --> 这很危险,第三个参数sdpacesUsed应该是 int& 而不是 double& This should not pass compile.这不应该通过编译。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM