0
int * addition(int arr[])
{
    int sum=0;
    for(int i=0;i<4;i++)
    sum+=arr[i];
    return &sum;
}

int main()
{
    int arr[4]{1,3,4,5}, * ptr=addition(arr);
    cout<<*ptr<<endl;
    return 0;
}

As the variable sum is local to the function addition so the variable should be destroyed as soon as the program control moves out of the function but it is still giving the output 13. Why?

Compiler: g++ 4.8.2 on Ubuntu 14.04 LTS

1 Answers1

0

The variable sum is on the stack. When the function addition() returns it doesn't zero the released stack memory, so the address returned still contains the sum.

Does it still work if you enable optimisation with -O3 ?

Hal
  • 1,061
  • 7
  • 20