浅析错误 Run-Time Check Failure #2 - Stack around the variable 'a' was corrupted

浅析错误 Run-Time Check Failure #2 - Stack around the variable 'a' was corrupted

  • 问题叙述
  • 解决方案
  • 结论

问题叙述

最近在写循环嵌套的时候老是报错:Run-Time Check Failure #2 - Stack around the variable ‘a’ was corrupted

百思不得其解,循环没有问题,网上查找错误,都说是内存越界造成的,于是各种扩大数组大小,仍然报错。
浅析错误 Run-Time Check Failure #2 - Stack around the variable 'a' was corrupted_第1张图片
以下是测试程序:

#include 
using namespace std;
#define MAX_AXES  4

int main()
{

	int axispos[MAX_AXES];
	int axisvel[MAX_AXES];
	int time[10] = { 0 };
	for (int i = 0; i < MAX_AXES; i++)
	{
		axispos[i] = i;
		axisvel[i] = i;
	}

	int a[10 * (MAX_AXES * 2 + 1)];
	for (int i = 0; i < 10; i++)
	{
		a[i*(2 * MAX_AXES + 1)] = time[i];
		cout << a[i*(2 * MAX_AXES + 1)] << "|";
		for (int j = 0; j < MAX_AXES; j++)
		{
			a[i*(2 * MAX_AXES + 1)+2*j-1] = axispos[j];
			a[i*(2 * MAX_AXES + 1) + 2 * j] = axisvel[j];
			cout << a[i*(2 * MAX_AXES + 1) + 2 * j - 1] << "|" << a[i*(2 * MAX_AXES + 1) + 2 * j] << "|";
		}
		cout << endl;
	}

	return 0;
}


在老王大腿的指导下,找到了问题所在。
在第2层循环中,有一句a[i*(2 * MAX_AXES + 1)+2*j-1] = axispos[j];,当i,j都为0的时候,a的索引变成了-1,于是引起数组越界问题。

解决方案

把循环从0开始换成从1开始

#include 
using namespace std;
#define MAX_AXES  4

int main()
{
	int axispos[MAX_AXES];
	int axisvel[MAX_AXES];
	int time[20] = { 0 };
	for (int i = 0; i < MAX_AXES; i++)
	{
		axispos[i] = i;
		axisvel[i] = i;
	}

	int a[10 * (MAX_AXES * 2 + 1)];
	for (int i = 0; i < 10; i++)
	{
		a[i*(2 * MAX_AXES + 1)] = time[i];
		cout << a[i*(2 * MAX_AXES + 1)] << "|";
		for (int j = 1; j <= MAX_AXES; j++) ///////////////////////////////
		{
			a[i*(2 * MAX_AXES + 1)+2*j-1] = axispos[j-1];
			a[i*(2 * MAX_AXES + 1) + 2 * j] = axisvel[j-1];
			cout << a[i*(2 * MAX_AXES + 1) + 2 * j - 1] << "|" << a[i*(2 * MAX_AXES + 1) + 2 * j] << "|";
		}
		cout << endl;
	}

	return 0;
}

为什么各种尝试都没有发现?原因在于形成了定式思维,一说超限首先想到的是上界超限,于是开始钻牛角尖………………

结论

  • 定式思维要不得!!!!

你可能感兴趣的:(▼,程序人生,#,▶,C/C++)