Thursday, 29 August 2013

Expecting SIGSEGV , but getting normal working

Expecting SIGSEGV , but getting normal working

I was working on a C output question:
#include<stdio.h>
int main()
{
int a[][2][3]={0,1,2,3,4,5,6,7,8,9,10,11,12};
int i=-1;
int d;
d=a[i++][++i][++i];
printf("%d\n",d);
return 0;
}
Link to Ideone: http://ideone.com/1oS9Un
and was expecting a runtime error, but surprisingly the code is working
fine on CodeBlocks,Dev C++ and Ideone.
According to me every memory address is resolved by compiler at runtime by
the following equation : a[i][j][k]= ((*(a+i)+j)+k), thus every compiler
should first resolve the inner parenthesis , then the next inner
parenthesis and so on.
Thus the given line
d=a[i++][++i][++i];
should be resolved as:
d=*(*(*(a+i++)+ ++i)+ ++i)
also by , http://www.difranco.net/compsci/C_Operator_Precedence_Table.htm
(Please refer note 2)
the innermost parenthesis should be resolved first, and it's value should
be a-1 , with i becoming 0. Thus we should get a SIGSEGV error as we are
trying to access memory not specifically marked by the compiler, still an
output is shown in all the three compilers. Please explain this.

No comments:

Post a Comment