+ 7

How is it possible? Please explain

#include <iostream> using namespace std; int main() { int arr[] = {8,6,4,5,7}; int sum = 0; for(int y = 0;y<9;y++) { sum+=arr[y]; } cout << sum; return 0; Ans = 6918870 }

12th Dec 2016, 3:18 PM
Nasim
Nasim - avatar
10 Answers
+ 5
A good example of why memory mis-management in C++ is dangerous 😉
12th Dec 2016, 5:43 PM
Kerrash
Kerrash - avatar
+ 4
yes it is possible because, you don't declared the length of your array in the beginning .
12th Dec 2016, 3:44 PM
Hassen Basdouri
Hassen Basdouri - avatar
+ 4
It takes junk values or unreleased values in those empty locations and add to the sum value.. so the answer is huge.
12th Dec 2016, 4:09 PM
Kaushik M
Kaushik M - avatar
+ 4
carefully see. array size is limited by its entries. with a loop going to 9, you are accessing junk values. ideally this should result in a segmentation fault
15th Dec 2016, 8:03 AM
Rohan Y.
Rohan Y. - avatar
+ 3
your array contains only 5 elements & you asked it sum more than 5 elements (9) here is thé problem
12th Dec 2016, 3:32 PM
Mehdi Bouzidi
Mehdi Bouzidi - avatar
+ 3
The memory cells that you don't have explicitly filled with values can contain any huge number 😅
13th Dec 2016, 1:41 PM
Teo Argentieri
Teo Argentieri - avatar
+ 3
Preprocessor and compiler allocates memory values to different program statements. Stack or heap allotted to compilers are fixed and these same data is used for many programs. Lets say, we have two programs. Now we executed first program successfully and if we want to execute second program, compiler allocates some part of memory to statements which is already used for some other program...all the memory is filled with garbage values...Because of improper initialisation and memory management, in the above program...garbage values are included in the sum.
15th Dec 2016, 8:08 AM
Manikanta Nallamalli (Mittu)
Manikanta Nallamalli (Mittu) - avatar
+ 3
5 elements in your array, but not spesified as 5 elements. so if you want to get a number like a[5], a[6],a[7], a[8] you will get the integer values in these memories and will change after usage of other programs.
17th Dec 2016, 4:14 PM
Ä°brahim BABAARSLAN
Ä°brahim BABAARSLAN - avatar
+ 2
8. Write a JavaScript function that accepts a number as a parameter and check the number is prime or not. Note : A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.
12th Dec 2016, 6:56 PM
Nashwan Aziz
Nashwan Aziz - avatar
+ 1
the compiler assigns address of sum= address of Arr[0]+20. so when y = 5..8, you end up adding address of sum, the address of base pointer and the return address of main.so you get a garbage value
27th Dec 2016, 7:32 PM
Suvaditya
Suvaditya - avatar