-1

i'm using code::bocks on GNU/linux/ I know what is segmentation fault, just curious what caused it in this case. why doest it return segmentation fault:

#include <iostream>
int main()
{
    using namespace std;
    int tab1[3];
        tab1[0] = 2 + 7 * 16 - 8;
        tab1[1] = 22 * 2 / 11;
        tab1[2] = 8383 - 222 + 292 * 8;
        tab1[3] = 5 * 2 * 4;

    cout << " " << tab1[1];
    return 0;
}

and this not

#include <iostream>
int main()
{
    using namespace std;
    int tab1[3];
        tab1[0] = 2 + 7 * 16 - 8;
        tab1[1] = 22 * 2 / 11;
        tab1[2] = 8383 - 222 + 292 * 8;
        tab1[3] = 5 * 2 * 4;

    cout << tab1[1];
    return 0;
}
sebek
  • 87
  • 1
  • 2
  • 8
  • 1
    `int tab1[3]` declares elements 0 through 2 inclusive. But you used 0 through 3. So both version of your program are broken. But sometimes undefined behavior has no visible symptom. So neither getting a seg fault nor not getting a seg fault should be surprising. – JSF Dec 10 '15 at 16:28
  • When you overwrite an array you get undefined behaviour. Basically the symptoms depend on what in memory you are attempting to overwrite. – Aumnayan Dec 10 '15 at 16:31
  • 0, 1, 2, 3, where's the last one gonna be? – Martin James Dec 10 '15 at 16:36

3 Answers3

3

You have declared the array tab1 to have space for 3 elements, but in the code you assign values to four elementes. tab1[3] = 5 * 2 * 4; writes to memory outside the array. It's probably just a coincidence that one program segfaults while the other does not.

1

You attempt to assign to tab1[3] which is outside of the array bounds. This is undefined behaviour and causing your segmentation fault.

Aiden Deom
  • 916
  • 5
  • 11
1

You are accessing the array with an index that's out-of-bounds.

int tab1[3];
tab1[0] = 2 + 7 * 16 - 8;
tab1[1] = 22 * 2 / 11;
tab1[2] = 8383 - 222 + 292 * 8;
tab1[3] = 5 * 2 * 4;  // <-- Error

Arrays start from index 0, and go up to n-1, where n is the total number of items in the array. Thus the largest index is 2 for an array with 3 items in it.

Now why the different behavior? Accessing an array out-of-bounds is undefined behavior. You cannot reliably predict what will happen when errors such as an out-of-bounds access occurs.

PaulMcKenzie
  • 34,698
  • 4
  • 24
  • 45