Domanda

This code on some compilers give different results in the mode with optimizations and without optimizations. This means that the code is invalid. What is it incorrect?

#include <stdio.h>
#include <stddef.h>

int a = 3;
int b = 5;

int
main (void)
{
  size_t delta;
  int *ptr;

  delta = &b - &a;
  ptr = &a + delta;

  printf ("%d\n", *ptr);
  return 0;
}
È stato utile?

Soluzione 3

The C standard operation difference pointers (and maybe all pointernaya arithmetic) is defined only for pointers, looking at the same object. The word "object" is meant here is that at the household level is called "variable" and not to C++ object. As a consequence, the total value of delta in terms of standard undefined.

On two compilers with a powerful context analyzer and hardware features done some tricky test has worked correctly. The test was in a slightly different form, but for simplicity, so leave.

Altri suggerimenti

Evaluating the expression &b - &a is undefined behaviour, since b and a are not subobjects of the same object.

You can only subtract pointers to elements of the same array, or one past the end. From the C++11 standard, 5.7.6:

Unless both pointers point to elements of the same array object, or one past the last element of the array object, the behavior is undefined.

As your code is more closer to C code then I will cite the C Standard. According to it

7 For the purposes of these operators, a pointer to an object that is not an element of an array behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type.

and

9 When two pointers are subtracted, both shall point to elements of the same array object, or one past the last element of the array object; the result is the difference of the subscripts of the two array elements.

In your example the two pointers do not point to elements of the same array. So the behaviour is undefined.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top