How is it possible? Please explain | Sololearn: Learn to code for FREE!


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 }

12/12/2016 3:18:51 PM


10 Answers

New Answer


A good example of why memory mis-management in C++ is dangerous πŸ˜‰


yes it is possible because, you don't declared the length of your array in the beginning .


It takes junk values or unreleased values in those empty locations and add to the sum value.. so the answer is huge.


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


your array contains only 5 elements & you asked it sum more than 5 elements (9) here is thé problem


The memory cells that you don't have explicitly filled with values can contain any huge number πŸ˜…


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.


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.


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.


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 you get a garbage value