0

I am trying to create a 3*N array where N is specified at runtime.

 int *array[3];
 int breadth;
 cin>>breadth;

    for(int i=0;i<3;i++)
        array[i] = new int[breadth];

    array[0][breadth-1] = 1;
    array[1][breadth-1] = 2;
    array[2][breadth-1] = 3;
    array[3][breadth-1] = 69; // how does this work

    cout<<array[3][breadth-1]<<endl;

The output is 69 and I am surprised that the indicated line works even though the maximum size (3) has been exceeded. Does anyone know why that element is accessible?

I tried other sizes like 4N and 5N, with the same results

toly
  • 1
  • 2
    No it only seems to work. You still don't have a valid program. Look up Undefined Behavior (UB). What happened is you wrote over some memory that could be in use by some other variable, But your program could also have crashed. C++ is like that it assumes you know what you are doing (to get performant code). Also this would have been a good canditate for using `std::array>` so you could write code without `new` (which is recommended). – Pepijn Kramer Dec 07 '22 at 03:42
  • The indicated may work today, but may crash tomorrow. Or it may always work, unless there's a full moon tonight. Or it may not work when it's raining outside. You just don't know, because this is undefined behavior. – Sam Varshavchik Dec 07 '22 at 03:48
  • Remember that C++ prizes speed above just about everything else, and a check to make sure the programmer's not dumb enough to write outside the buffer wastes time. – user4581301 Dec 07 '22 at 04:01
  • Run your program with ubsan enabled and watch it fail. – Ben Dec 07 '22 at 04:23
  • Thank you all. Indeed it is correctly (and incredibly) resulting in a segfault when I add more comments to the code. Good to know. – toly Dec 07 '22 at 05:57
  • @toly The thing to realise is that such things are *undefined* by the standard. There isn't a guarantee of anything - a segfault *may* occur, but lack of a segfault doesn't mean the code is correct in any way. So the same code may give different observable behaviours with other compilers, with different compilation (e.g. optimisation) options, or even with phase of the moon. – Peter Dec 07 '22 at 06:13
  • Consider segfaults to be gifts from whatever deities you worship. They tell you without ambiguity that there is a problem with the code. Not getting a segfault doesn't tell you that you don't have problems, but that any problems you do not yet know about simply didn't result in a segfault. – user4581301 Dec 07 '22 at 17:58

0 Answers0