【问题标题】:Template program keeps crashing模板程序不断崩溃
【发布时间】:2011-06-10 11:41:52
【问题描述】:

我的程序可以正常编译和运行,但是当我在程序中时它崩溃了。 知道为什么吗?

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

【问题讨论】:

  • 在调试器或 valgrind 之类的工具下运行它。显然,模板不会直接使您的程序崩溃,因为它们是编译时而非运行时构造。如果您无法使用调试器解决此问题,请尝试将其归结为一个更简单的示例,并向我们展示您遇到的错误。

标签: c++ crash


【解决方案1】:

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

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

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

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

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

【讨论】:

  • 感谢您帮助我修复了我的程序
【解决方案2】:

问题:

  • maxSize 可以大于SIZE --> 数组越界

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

  • fillDoubleArray(dArray,SIZE,dspacesUsed); --> 这很危险,第三个参数sdpacesUsed 应该是 int& 而不是 double&。这不应该通过编译。

【讨论】:

    猜你喜欢
    • 2015-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多