This is a simple code just to illustrate the issue I am dealing with.
If you give the input of n = 3 and enter the array elements as 1, 2 ,3 and m= 0 the program crashes!!!
Why is it so?? The problem occurs due to the last 2 lines involving the free()
Now my question is why this thing is happening? The same program with the same input doesn't crash if the free statements are removed...
Please explain me. Is it so that the conditional memory allocation is causing the said problem to occur?? If so then why ?
I am not getting any cue, moreover free (NULL) shall not cause any error as far as I know, so the problem is caused when I am trying to free one of the allocated memory, especially positive in my input ...
This is my code:
#include <stdlib.h>
#include <stdio.h>
int main()
{
int n;
scanf("%d",&n);
printf("Enter elements into the array\n");
int arr[n];
int i;
for(i=0;i<n;)
{
printf("arr[%d] ? ",i);
scanf("%d",(arr+i));
if(i>0)
{
if(arr[i]<arr[i-1])
continue;
else
i++;
}
else
i++;
}
int m;
printf("m ? ");
scanf("%d",&m);
int j,flag=0;
int *positive,*negative;
int start,end;
start=arr[0];
end=arr[n-1];
if(start<0 && end<0)
{
negative=(int*)calloc((start*-1),sizeof(int));
positive=0;
}
else if(start<0 && end>0)
{
negative=(int*)calloc((start*-1),sizeof(int));
positive=(int*)calloc(end,sizeof(int));
}
else if(start>=0 && end >0)
{
negative=0;
positive=(int*)calloc(end,sizeof(int));
}
int p=0;
for(i=0;i<n;i++)
{
if(i==0)
p=-1;
else
p=i;
if(arr[i]<0)
negative[-arr[i]]=p;
else
positive[arr[i]]=p;
}
for(i=0;i<n;i++)
{
int num=m-arr[i];
if(negative!=0 && num<0 && negative[-num])
{
if(negative[-num]==-1)
j=0;
else
j=negative[-num];
printf("%d %d\n",i,j);
flag=1;
}
else if(positive!=0 && num>=0 && positive[num])
{
if(positive[num]==-1)
j=0;
else
j=positive[num];
printf("%d %d\n",i,j);
flag=1;
}
}
if(flag==0)
printf("NO SUCH i j EXISTS\n");
if(positive) free(positive);
if(negative) free(negative);
return 0;
}
Here is my output:
With the input values you mention, you first do :
end=arr[n-1];
positive=(int*)calloc(end,sizeof(int));
Given that n == 3
and arr[n-1] == 3
, you allocate an array of 3 int
s for positive
.
In the very next loop, you then end up doing :
positive[arr[i]]=p;
which tries to overwrite positive[3]
(when i == n-1
). This is trying to write beyond the bounds of the array (valid indexes range from 0
to 2
only), and undefined behavior ensues, meaning anything at all can happen after that point, including a crash.