-2

When the variable num is used it I get a stack corrupted error while I'm accessing the 9th index but when I access with any other name it gives an error. Please explain me this ambiguity.

#include<iostream>
#include<iomanip>
using namespace std;
const int SIZE = 9;

class A
{
private:

    int num[SIZE];
    int num_2[SIZE];
public:
A()
{
    for(int i = 1 ; i <= 9 ; i++)
    {
        num_2[i] = i;
    }  
}
};
void main()
{
    A obj;
}
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
Junaid Lodhi
  • 331
  • 4
  • 9
  • 2
    Side comment: your code is incorrect, it's `int main()`, not `void`. See http://en.cppreference.com/w/cpp/language/main_function – kebs Dec 28 '15 at 17:45

2 Answers2

6

If SIZE = 9 then your loop should be

for(int i = 0; i < SIZE ; i++)

C++ uses 0-based indexing, so the first index of the array is [0] and the last is [SIZE-1]

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • but when i use num variable,... it does npt give error ??? why but it gives error when using variable anyother variable name – Junaid Lodhi Dec 28 '15 at 17:44
  • 1
    @JunaidLodhi Assigning to an [array out of bounds](https://stackoverflow.com/questions/1239938/c-accesses-an-array-out-of-bounds-gives-no-error-why) is [undefined behavior](https://stackoverflow.com/questions/367633/what-are-all-the-common-undefined-behaviours-that-a-c-programmer-should-know-a). It could do anything. It could perform the assignment, throw an exception, blow up your computer... anything! You saw that the same mistake with two different arrays resulted in two different behaviors, I hope that proves my point. – Cory Kramer Dec 28 '15 at 17:45
  • if it's an exception then brother it wasted my hours.... just to check why it's not giving error for num and giving error for num_2 – Junaid Lodhi Dec 28 '15 at 17:50
  • As I said it is undefined behavior. It is possible to get a [`SEGFAULT`](https://stackoverflow.com/questions/2346806/what-is-segmentation-fault), [stack corruption](https://stackoverflow.com/questions/718503/stack-corruption-in-c), or maybe nothing! It depends on what is at that memory location already and what your computer decides to do about it! – Cory Kramer Dec 28 '15 at 17:53
1

The problem is i <= 9
num_2[9] is beyond the end of num_2

JSF
  • 5,281
  • 1
  • 13
  • 20