0

My array is of size 3x3 means i have values of index from 0 to 2 only. but when i traverse using for loop then why it is picking value of a[3][-3] on value of a[2][0] ???

and what is that error when i try a[3][3] it should give garbage value so why this error

*** stack smashing detected ***: terminated

#include <bits/stdc++.h>
#include <iostream>
#define vi vector<int>
using namespace std;

int main()
{
    char a[3][3];
    int pos, row, col;
    cin >> pos;
    memset(a, 48, sizeof(a));
    //row = pos / 3;
    //col = pos % 3 - 1;
    a[3][3] = 'X';
    //a[3][-3] = 'X';
    for (char *b : a)
    {
        for (size_t i = 0; i < 3; i++)
        {
            cout << b[i] << " ";
        }
        cout << endl;
    }
}

for a[3][-3] result will be output:

0 0 0
0 0 0
X 0 0

for a[3][3] result will be output:

0 0 0
0 0 0
0 0 0
*** stack smashing detected ***: terminated
Aborted (core dumped)
Kuldeep Soni
  • 43
  • 1
  • 6
  • 2
    You said it yourself: index values in an array of size 3 can only range between 0 and 2. So how can you possibly expect `a[3][3] = 'X'` to be valid? The result of doing something like that is *undefined behavior* - you *might* get a garbage value, but you might also cause a crash, or data corruption, or worse. Just don't do it. – Nate Eldredge Jun 24 '20 at 13:35
  • 7
    "*it should give garbage value*" No, it's undefined behavior. The behavior you're seeing here is probably the best that could happen. The worst is when it seems like it works until you release your code to the world and *then* it blows up! – Kevin Jun 24 '20 at 13:37
  • While `a[3][-3]` has undefined behaviour, there is an explanation for the result: it is three `char`s backwards from the non-existent first element of the non-existent fourth array, which happens to be the first element of the third array. – molbdnilo Jun 24 '20 at 13:58

2 Answers2

3

For an array like a[3][3], indexing into a with [3][3], or [3][-3] invokes undefined behavior. Anything can happen, including printing out garbage values. The program is not even guaranteed to print a value, it could simply crash.

The only valid indexes for either bound is 0, 1, and 2.

Note that even if you index into a correctly, reading from a is also undefined behavior, since you have not initialized a. You can do that like this:

char a[3][3]{};

and now reading from, say a[2][0] is fine.

cigien
  • 57,834
  • 11
  • 73
  • 112
0

This is because of wrong arithmetic as @Kevin answer in comment that

a[2][0] = 2*3 + 0 = 6 bytes

and also

a[3][-3] = 3*3 - 3 = 6bytes

so both pointing to same value.

Kuldeep Soni
  • 43
  • 1
  • 6