问题描述:使用C++函数模板技术编写了一段数组排序的代码,编译环境无报错,但是编译后运行时报错,提示“该变量周围的堆栈区被破坏了”。
开发环境:Win10 + VS2022
错误分析:提示堆栈区被破坏,代码中使用到堆栈区的有数组,可能会造成数组访问越界的问题,即原开辟空间不够用
源代码:
#include<iostream>
#include<string>
using namespace std;
//交换函数模板
template<class T>
void mySwap(T& a, T& b) {
T temp = a;
a = b;
b = temp;
}
//排序函数模板
template<class T>
void mySort(T arr[], int len) {
for (int i = 0; i < len; i++) {
int max = i;//认定最大值的下标
for (int j = i + 1; j < len; j++) {
if (arr[max] < arr[j]) {
max = j;
}
}
if (max != i) {
mySwap(arr[max], arr[i]);
}
}
}
//打印数组模板
template<class T>
void printArray(T arr[], int len) {
for (int i = 0; i < len; i++) {
cout << arr[i];
}
cout << endl;
}
void te