Will the pointer at the ends overlap with another object?

Given that C ++ has no binding for built-in type arrays, is it possible that:

Does one pointer to one array point to the first element of the first array?

+4
source share
4 answers

Yes, a pointer beyond the end of an array can point to another object. Allocating a pointer outside the array results in undefined behavior.

+4
source

My opinion: yes, it is possible in C ++. There were several SO threads on this topic, none of which reached any solid conclusion. Here is one example .

, . - ; - . , , , - , " " .

struct
{
    int a[2];
    int b[2];
} foo;

if ( sizeof foo == 4 * sizeof(int) )
{
    int *p = &foo.a[0];

    ++p;    // (1)
    ++p;    // (2)
    *p = 3; // (3)
    ++p;    // (4)
    *p = 5; // (5)
}

undefined ( )? p (, ) int[2], foo.a.

(2), p . ?

+ ( p p = p + 1). ++ 11 [expr.add] # 7:

, undefined.

(2) UB . (3)?

, ++ , " ", undefined. , " ", " , ". : " ".

, , , , ; , p foo.b[0]. p foo.b, foo.a.


, C99 . C99 + ( ):

, ; undefined. , * , .

, C99 (3) undefined. ++ .


: , . " " C- , " ", . (), ; .

, C99 ; , (3).

, , ++ , ++ (3), UB; (4), (5).

+2

.

  • , .
  • ,
  • int 4- , .
  • , . !

.

Kajal

+1

, :

?

I'm not sure what you mean by the end pointer. Since C ++ iterators use half of the open ranges, I assume you mean a pointer that represents the end position in the iteration. Since this is one end, yes, it can overlap the next array, and therefore, it cannot be dereferenced.

When using pointers as iterators, addresses are compared, not values. End means the next address outside the end.

+1
source

Source: https://habr.com/ru/post/1546641/


All Articles