Wednesday 15 August 2012

c - Why are the values same? -


I am unable to understand the fragment of this code. I do not understand that the values ​​of SX, SA, SI are same, i.e. 42. I think it has to do something with pointers. If someone can explain

  #include & lt; Stdio.h & gt; Stable Intel SX; Fixed integer [100]; Static int sy; Int main () {int * p; (P = & amp; sx; p & lt; = & amp; sx + 200; p ++) {* p = 42; } Printf ("sx = \ t% i \ n", sx); Printf ("sa [0] = \ t% i \ n", sa [0]); Printf ("sa [109] = \ t% i \ n", sa [109]); Printf ("sy = ​​\ t% i \ n", sy); Getchar (); }   

You are writing beyond the limit of one variable and therefore it is For unspecified behavior (p = & amp; sx; p & lt; = & amp; sx + 200; p ++) {* p = 42; }

This code snippet writes beyond memory that was allocated for sx and causes undetermined behavior. Note p pointer sx and sx is only an integer and there is no array that the loop writes over and over the memory that sx Is allocated for.

Undefined behavior does not require a program crash, this means that the program can be anything to produce. It may or may not appear to work or show some strange results, in simple words any result is possible.

No comments:

Post a Comment