stack around the variable 'X' is corrupted

hey guys ,
I have been trying to solve a problem when this error came to me :
" stack around the variable 'X' is corrupted "
the program is working correctly and it gave me the wanted result but why does this error appear ?

this is my code :
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class interval
{
public:
int a;// lower bound
int b;// upper bound
interval(int aValue, int bValue) {set(aValue,bValue);};
interval() {set(0,0);};
void set(int aValue, int bValue) {a=aValue;b=bValue;if(a>b) exit(0);};
void print() {cout<<"["<<a<<","<<b<<"]";}
};


bool check(const interval A[], int n, int X[], int d)
{
	int j=0 ; 
	X[j] = A[0].a ;
	j++;
	for( int i=0 ; i<n ; i++ )
	{
		if( X[j] + d > A[i+1].b )
			return false ;
		if( A[i].a + d <= A[i+1].a )
		{
			X[j]=A[i+1].a;
			j++;
			continue;
		}
		// X[j]+d between A[i+1].a and A[i+1].b 
		X[j]=X[j-1]+d;
		j++;
	}
	return true;
}

void printArray( int A[] , int n )
{
	for( int i=0 ; i<n ; i++ )
		cout<<A[i]<<"  ";
	cout<<endl;
}

int main ()
{
	interval A[4] ;
	A[0].set(0,1);
	A[1].set(3,6);
	A[2].set(7,10);
	A[3].set(13,16);
	int X[4];
	if( check(A,4,X,5) == true ){ cout<<" Yes "<<endl; printArray( X,4) ;}
	else cout<<" No "<<endl;
	if( check(A,4,X,6) == true ){ cout<<" Yes "<<endl; printArray( X,4) ;}
	else cout<<" No "<<endl;

	return 0;
}

 



Thanks in advance for everyone who replies :)
On line 29: What happens if X[j]=X[j-1]+d; // j=0 ?

On line 20/22/24: i+1 is out of bounds if i=3
for the j : I took the case where j=0 before entering the for loop ..

for i : Can you please suggest how can i fix it ?
ohhh No worries I got the mistake :)
you were right it have to do with i :P
and a couple of other things too ..

this is the new code with the modification :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
bool check(const interval A[], int n, int X[], int d)
{
	int j=0 ; 
	X[j] = A[0].a ;
	j++;
	for( int i=0 ; i<n-1 ; i++ )
	{
		if( X[j-1] + d > A[i+1].b )
			return false ;
		if( X[j-1] + d <= A[i+1].a )
		{
			X[j]=A[i+1].a;
			j++;
			continue;
		}
		// A[i].a+d between A[i+1].a and A[i+1].b 
		X[j]=X[j-1]+d;
		j++;
	}
	return true;
}



Thanks Alot i couldn't done it without you :) Regards
Last edited on
Topic archived. No new replies allowed.