0

So, I got an example in a book:

int * func()
{
    int A[3][3] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    return (int*)A;
}

void main(void)
{
    int *a = func();
    cout << *(a + 2*3 + 1);
    system("PAUSE");
}

I tried running this and its working fine.

My question is we are providing stack memory inside func() routine which should be available (compiler can assign some other variable at same address) after the exit from func(). Is it a correct way? I think this could lead to UnDefined Behaviour sometime..

cosmos
  • 2,263
  • 1
  • 17
  • 30
  • It **is** undefined behavior! – πάντα ῥεῖ Apr 19 '14 at 09:21
  • “It seems your code got away with it this time, you wascawwy wascal! I'll get you next time, Gadget!” (UB isn't required to crash or to fail when executed. It's also not required to not set fire to the local nunnery. Undefined means _undefined_.) – Donal Fellows Apr 19 '14 at 15:05

1 Answers1

0

You are quite right: the code exhibits undefined behaviour.

On the other hand, if A were static or heap-allocated, the situation could be rather different.

NPE
  • 486,780
  • 108
  • 951
  • 1,012