Well on a regular basis i get obstructed with this error , the monitored command dumped core.
Which is pretty much alien language to me, hence i cannot not possibly understand what the compiler is saying.
I looked up the internet , for what could be the reason and found out that i could be accessing index which has not been allocated memory, therefore i set on to make a simplest code possible and encounter the same error.
#include<stdio.h>
int main()
{
int n;
int a[100000];
scanf("%d",&n);
int j=0;
for(int i=2;i<=n;i+2)
{
if (i%2==0)
{
a[j]=i;
j+=1;
}
}
return 0;
}
But i don't understand how i could be accessing non allocated memory.
Also what could be the other reasons for the same error to occur such frequently.
I think the issue could be your for
loop, as in the third part you're not updating i
. To update, write it as i=i+2
or i+=2
.
Your index j
gets out of bounds:
Demonstration:
#include<stdio.h>
int main()
{
int n;
int a[100000];
scanf("%d", &n);
int j = 0;
for (int i = 2; i <= n; i + 2)
{
if (i % 2 == 0)
{
if (j > 100000) // <<<<<<<<<<<<<<
{
printf("Bummer\n");
return 1;
}
a[j] = i;
j += 1;
}
}
return 0;
}
Accessing an array with out of bounds results undefined behaviour (google that term).
You are incrementing the value of i. You have written i+2 instead of i+=2.
#include<stdio.h>
int main()
{
int n;
int a[100000];
scanf("%d",&n);
int j=0;
for(int i=2;i<=n;i+=2)
{
if (i%2==0)
{
a[j]=i;
j+=1;
}
}
return 0;
}
You are writing i+2 ,but you have to write i+=2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With