WA in CINEMA of codemutants

i don’t understand why this solution of mine is giving WA. works perfectly on ideone.

#include<stdio.h>
main()
{
int t,test,m,n,p,q,i,j,k,l,flag=1,x,y,c=0;
char a[1005][1005];
int ma[1005],na[1005];
scanf("%d",&t);

for(test=0;test<t;test++)
{
	scanf("%d",&m);
	scanf("%d",&n);
	
	scanf("%d",&p);
	scanf("%d",&q);
	
	for(i=0;i<m;i++)
	{
		getchar();
		for(j=0;j<n;j++)
		{
			scanf("%c",&a[i][j]);
		}
	}
	
	for(i=0;i<=m-p;i++)
	{
		for(j=0;j<=n-q;j++)
		{
			flag=1;
			if(a[i][j]=='#')
			{
				for(k=i;k<(p+i);k++)
				{
					for(l=j;l<(q+j);l++)
					{
						if(a[k][l]!='#')
						flag=0;
					}
				}
				if(flag==1)
				{
				
				ma[x++]=i;
				na[y++]=j;
				c++;
				}	
			 }
		}
	}
	if(c!=0)
	{
	printf("%d\n",c);
	for(i=0;i<x;i++)
	printf("%d %d\n",ma[i],na[i]);
	c=0;
	}
	else
	printf("0\n");
	x=y=0;
	flag=1;

}
}

The problem with the code is that you are not re-initializing the array after each iteration. As you are not re-initializing the arrays neither checking the bounds of inner two “for loops” which are from k=i to k=p+i and l=j to l=q+j, in cases it may go out of bounds. If in one iteration value n and m are large and in next case they are small, then you are still accessing array values which are not valid for the present loop. Hence bound on array need to be given.

//