×

 0 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 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); }  asked 19 May '17, 19:10 6●1 accept rate: 0% 15.5k●1●20●66 1 Write header file correctly (19 May '17, 19:59) Header is correct but it is showing error as SIGABRT (19 May '17, 20:41) Please try to comment such one liners. (19 May '17, 22:07)

 2 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 :P answered 20 May '17, 00:37 6★meooow ♦ 7.3k●7●20 accept rate: 48% This undefined behaviour is the reason of half of my debugging troubles. Hard to figure out! (20 May '17, 00:48)
 0 Declare array outside the int main and try once,let me know if this doesn't work answered 19 May '17, 22:53 1.7k●2●10 accept rate: 14%
 0 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. answered 19 May '17, 22:59 2.5k●4●21 accept rate: 17%
 toggle preview community wiki:
Preview

By Email:

Markdown Basics

• *italic* or _italic_
• **bold** or __bold__
• image?![alt text](/path/img.jpg "title")
• numbered list: 1. Foo 2. Bar
• to add a line break simply add two spaces to where you would like the new line to be.
• basic HTML tags are also supported
• mathemetical formulas in Latex between \$ symbol

Question tags:

×2,738
×170

question asked: 19 May '17, 19:10

question was seen: 250 times

last updated: 20 May '17, 00:48