Question with error in Visual Studio

Good evening, I'm doing an exercise in C. The result is correct, but I get the following error in Visual Studio:. "Run-Time Check Failure # 2 - Stack around the variable 'n' was corrupted"

Can you help me identify the error?

Below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#define _CRT_SECURE_NO_WARNINGS

#include <stdlib.h>
#include <stdio.h>

#define TAM 1000

void main()
{
	int i, a, t, n[TAM];
	i = 0;

	printf("Enter a value T: ");
	scanf("%i", &t);

	if (t >= 2 && t <= 50)
	{
		while (i < TAM)
		{
			for (a = 0; a < t; a++)
			{
				n[i] = a;
				i++;
			}
		}

		for (i = 0; i < TAM; i++)
		{
			printf("%i\n", n[i]);
		}
	}

	system("pause");
}


Thank you!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#define _CRT_SECURE_NO_WARNINGS

#include <stdlib.h>
#include <stdio.h>

#define TAM 1000

void main()
{
	int i, a, t, n[TAM];
	i = 0;

	printf("Enter a value T: ");
	scanf("%i", &t);

	if (t >= 2 && t <= 50)
	{
		while (i < TAM)
		{
			for (a = 0; a < t; a++)
			{
				n[i] = a; //!!! you're not checking if subsequent i values are less than TAM
				i++; //HERE, you increment i without checking if(i < TAM)
			}
		}

		for (i = 0; i < TAM; i++)
		{
			printf("%i\n", n[i]);
		}
	}

	system("pause");
}
Last edited on
I made the correction and stood as the code below, right? But the error continues ...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#define _CRT_SECURE_NO_WARNINGS

#include <stdlib.h>
#include <stdio.h>

#define TAM 10

void main()
{
	int i, a, t, n[TAM];
	i = 0;

	printf("Enter a value T: ");
	scanf("%i", &t);

	if (t >= 2 && t <= 50)
	{
		while (i < TAM)
		{
			for (a = 0; a < t; a++)
			{
				n[i] = a;
				if (i < TAM)
				{
					i++;
				}
			}
		}

		for (i = 0; i < TAM; i++)
		{
			printf("%i\n", n[i]);
		}
	}

	system("pause");
}
I made the correction and stood as the code below, right?

No. You need to check the value of i before you use it as an index.
Topic archived. No new replies allowed.