admin管理员组文章数量:1618722
Run-Time Check Failure #2 问题
报错:Run-Time Check Failure #2 - Stack around the variable ‘a’ was corrupted.
简单来说,错误原因是:栈被破坏,缓存区溢出。
解决措施有两项:
一。这个措施是在CSDN上找到的,正确性待定
把 project->配置属性->c/c+±>代码生成->基本运行时检查 为 默认值 。
这个方式又导致了我代码其它错误,所以也不确定是否正确
二。堆栈的数组溢出
假设在代码中定义了a[3]数组,但最终存储了4个数值,就导致了溢出,这个是我的错误原因。
下面是我的代码,目的是分治法解决中位数问题:
问题描述
设X[ 0 : n - 1]和Y[ 0 : n – 1 ]为两个数组,每个数组中含有n个已排好序的数。找出X和Y的2n个数的中位数。
编程任务
利用分治策略试设计一个O (log n)时间的算法求出这2n个数的中位数。
数据输入
由文件input.txt提供输入数据。文件的第1行中有1个正整数n(n<=200),表示每个数组有n个数。接下来的两行分别是X,Y数组的元素。
实现提示
比较两个序列的中位数大小,如果两个数相等,则该数为整个2n个数据的中位数,否则通过比较,分别减少两个序列的查找范围,确定查找的起止位置,继续查找。
代码如下:
#pragma warning(disable : 4996)
#include<iostream>
using namespace std;
int n;
float Median(int a[], int b[], int mida, int midb)
{
if (a[mida] == b[midb])//两中位数相等
return a[mida];
else if (a[mida] < b[midb] && (b[midb] < a[mida + 1] || a[mida + 1] == 0))
return a[mida]; //a中位数比b中位数小且b中位数比a[mida+1]小,或a[mida+1]空
else if(a[mida] > b[midb] && (a[mida] < b[midb + 1] || b[midb + 1] == 0))
return b[midb]; //a中位数比b中位数大且a中位数比b[midb+1]小,或b[midb+1]空
else if (a[mida] < b[midb])//a中位数比b中位数小,a选右,b选左
return Median(a, b, (mida + n) / 2, (midb + 1) / 2);
else if (a[mida] > b[midb])//a中位数比b中位数大,a选左,b选右
return Median(a, b, (mida + 1) / 2, (midb + n) / 2);
}
int main()
{
//int a[] = { 0 }, b[] = { 0 };会导致堆栈溢出错误
int a[10] = { 0 }, b[10] = { 0 };
FILE* fp = NULL;
fp = fopen("input.txt","r");//打开只读文件
if (!fp)
{
cerr << "input.txt访问失败!" << endl;
return 0;
}
fscanf(fp, "%d", &n); cout << n << endl;
for (int i = 0; i < n; i++)
{
fscanf(fp, "%d", &a[i]);
cout << a[i] << " ";
}
cout << endl;
for (int i = 0; i < n; i++)
{
fscanf(fp, "%d", &b[i]);
cout << b[i] << " ";
}
fclose(fp);
cout << endl;
system("pause");
int mid;
mid = Median(a, b, n / 2, n / 2);
cout << mid << endl;
fp = fopen("output.txt", "w");//打开只写文件
if (!fp)
{
cerr << "output.txt访问失败!" << endl;
return 0;
}
fprintf(fp,"%d",mid);
fclose(fp);
system("pause");
return 0;
}
版权声明:本文标题:Run-Time Check Failure #2 问题 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/dongtai/1728785466a1173269.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论