Please help in SIGABRT and INTSET

Can any one help me in identifying the error in this code and reason for this error SIGABRT?

Question Enormous Input test code INTSET ?

#include<bits/stdc++.h>
using namespace std;
int main()
{
 long long int n,k,i,a,co=0;
 scanf("%lld%lld",&n,&k);
 long long int arr[n];
 for(i=0;i< n;i++)
 {
  scanf("%lld",&arr[i]);
 }
 for(i=0;i< n;i++)
 {
  if(arr[i]%k==0)
        co++;
 }
 delete[] arr;
 printf("%lld\n",co);
}

Declare array outside the int main and try once,let me know if this doesn’t work

Can’t believe I didn’t notice that. Your main function is supposed to return an int. add return 0 at the end of the function.

You are getting SIGABRT because the argument to delete[] must be a pointer to some block of memory that can be deallocated. However, your array arr is declared as a constant size array, so it does not qualify and you get undefined behaviour.
But you might say that it is not a constant size array since its size is provided during runtime. Your array arr is actually what is called a variable length array. VLAs are not a part of the C++ standard, however the gcc compiler (under which your submission was made) allows it. So you don’t get a compilation error and it works, but you cannot free that memory because it is treated by delete[] as a constant size array. Hope that made sense.
The fix is to change “long long int arr[n];” to “long long int *arr = new long long int[n];”. Now arr is dynamically allocated which can be freed by delete[]. Or maybe just don’t free the memory, it’s only competitive coding :stuck_out_tongue:

2 Likes

This undefined behaviour is the reason of half of my debugging troubles. Hard to figure out!