For the next program fragment, write in the form of a table the value of the variables after each step of the program (the columns correspond to the variables, the rows to the rows of the program). Type int and pointers occupy 4 bytes each. The compiler arranged the variables at the following addresses: a - 100, p1 - 120, p2 - 124, sx - 128, sy - 132. The number N is the number of the variant.

struct str {int x; int y;}; int a[5] = {1, 2, 3, 4, 5}; int *p1, *p2; str s; p1 = &a[N%5+1]; //первая строка таблицы p2 = a+N/5+1; //2-я строка sx = *p1; //3-я строка sy = *p2++; //4-я строка *(p1-2)=sy; //5-я строка p2=&s; //6-я строка p2->x=p1[1]; //7-я строка p2–>y=sy; //8-я строка a[5]=sx; //9-я строка 

The table, as I understand it, should be 5 columns and 9 rows with values. enter image description here something like this? Only here in the 8th line I did not understand - is the assignment of the value to itself? Because p2 refers to s.

Added! Oh yes, N = 2.


Calculated table

Found and corrected the shortcomings, that’s about everything in the table. Line 7 is not quite clear - is the pointer to the element of the array? or it points to an element with an index of 1 array (as I am in the table and designed). The teacher said that there are errors in the code that need to be fixed, besides the incorrect declaration of the structure s mb here is also a mistake? still not like line 8 - so you can declare? Well, in general, not sure that everything is filled correctly. Interested in line 2.

  • Yes, the 8th line does nothing. - dzhioev 4:08
  • one
    Since this is clearly a learning task, why don't you ask your lecturer? - VladD

1 answer 1

By standard, access to unallocated memory has undefined behavior. Therefore, the code p1 = &a[N%5+1]; ... *p1 p1 = &a[N%5+1]; ... *p1 for the case of N = 4 incorrect. The same applies to the code p2 = a+N/5+1; ... *p2 p2 = a+N/5+1; ... *p2 for the case of N = 20 .

The address at which the compiler puts which variable is not important. UB is UB, and the compiler has the right to do anything in the event that it occurs.

If your teacher does not know this, he is stuck in the Mesozoic, in which the compilers did not know how to optimize (and do not know the standard of the language). You cannot rely on any behavior with UB, unless your particular compiler guarantees it.

Be sure to read carefully: A Guide to Undefined Behavior in C and C ++, part 1 , part 2 , part 3 .

  • I understand what you mean, yes, it turns out badly, but this is just a university. And the assignment in the last stock is also not very good? - user193688
  • @user193688: Similarly. And if the code I quoted is UB only for special values ​​of N , then a[5] is UB in any case. - VladD 5:27