What harm arises from pointer arithmetic outside the allowable memory range?

I followed the discussion of A single byte pointer that is still valid in C? .

The point of this discussion, as far as I could understand, was that if you have:

char *p = malloc(4);

Then you can get the pointers to p+4using pointer arithmetic. If you get a pointer with p+5, then the behavior is undefined.

I see why dereferencing p+5can lead to undefined behavior. But is undefined behavior using only pointer arithmetic?

Why arithmetic operators +and -were not real transactions? I do not see any harm by adding or subtracting a number from the pointer. After all, a pointer is a number that captures the address of an object.

Of course, I was not in the standardization committee :) I do not participate in the discussions that they had before the codification of the standard. I'm just curious. Any insight would be helpful.

+4
source share
4 answers

, , . , , , , , . C , C , , .

, , ( 0s) . , , . , , C .

, , , . :

if (iter - 1 < object.end()) {...}

, iter, ( ) object. UB , , iter (, , , object), . , :)

, , unspecified undefined. ( ) == , . , a b , end_a a begin_b b,

end_a == begin_b

; 1 , b a , 0. ( a b ), ; undefined, 0, 1 (, , , , .)

+4

, + - .

, , , p = malloc(4) p+4 . , , , p+4 . , p+5 .

+ - , , , , .

+2

+/- . : &p[0] < &p[1] < ... &p[n] n. . &p[-1] &p[0].

int *p = malloc(80 * sizeof *p);
int *q = p + 1000;
printf("p:%p q:%p\n", p, q);

, .

printf("*p:%d\n", *p);  // OK
printf("*p:%d\n", p[79]);  // OK
printf("*p:%d\n", p[80]);  // Bad, but &p[80] will be greater than &p[79]
printf("*p:%d\n", p[-1]);  // Bad, order of p, p[-1] is not defined 
printf("*p:%d\n", p[81]);  // Bad, order of p[80], p[81] is not defined
char *r = (char*) p;
printf("*p:%d\n", *((int*) (r + 1)) );  // Bad
printf("*p:%d\n", *q);  // Bad

: p[81] undefined?
A: : 0 N-1. char *p N-81. p[0] p[79] . p[80] . p[81] , n , , p[81] 0, N .

+1

, p + 4 , .

p + 5 would not theoretically be a problem, but in my opinion the problem would be that you try to dereference (p + 5) , or maybe you will try rewriting that address.

0
source

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


All Articles