-2

Is this a segmentation error or not? Why not? Please answer me, why this doesn't give me segmentation error?

#include <iostream>

using namespace std;

int main()
{
    int ** T;
    T = new int*[5];
    for(size_t i=0; i<5; i++){
        T[i] = new int[5];
    }
    T[4][7] = 10;
    return 0;
}
pzaenger
  • 11,381
  • 3
  • 45
  • 46
MrOutadi
  • 52
  • 4
  • 3
    Undefined Behaviour is *undefined*. It may crash, it may work fine, it may [make demons fly out of your nose](http://catb.org/jargon/html/N/nasal-demons.html). – Yksisarvinen Mar 15 '20 at 13:06
  • Does [Undefined, unspecified and implementation-defined behavior](https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior) answer your question? – Ted Lyngmo Mar 15 '20 at 13:09
  • Correct answer by @Yksisarvinen. However, if you want to make sure buffer overruns trigger catastrophic failures, compile your program with `-fsanitize=address` (works on gcc and clang) and it will complain about your out-of-bounds access with a detailed diagnostic. – bitmask Mar 15 '20 at 13:24

1 Answers1

1

Looks OK to me except for the 7 at the end. T is a pointer to pointer to ints, and it's assigned to an array of 5 pointers to ints (OK so far). Then each member of that array is assigned to a pointer to 5 ints. Still fine. Lastly, T[4] is a pointer to ints, but only 5 are assigned. So T[4][7] goes off the end of the array.

Now, will this actually segfault? That depends on memory alignment. If that address, &T[4][7] is on a different memory page than the actual allocated array, you'll get a segfault. Otherwise, you're just reading unallocated memory and you get whatever's there.

GaryO
  • 5,873
  • 1
  • 36
  • 61