Assign a random address to a pointer to void and increment it

  • A+
Category:Languages

Is the behaviour of this code well defined?

#include <stdio.h> #include <stdint.h>  int main(void) {     void *ptr = (char *)0x01;     size_t val;      ptr = (char *)ptr + 1;     val = (size_t)(uintptr_t)ptr;      printf("%zu/n", val);     return 0; } 

I mean, can we assign some fixed number to a pointer and increment it even if it is pointing to some random address? (I know that you can not dereference it)

 


The assignment:

void *ptr = (char *)0x01; 

Is implementation defined behavior as per section 6.3.2.3 of the C standard regarding Pointers:

5 An integer may be converted to any pointer type. Except as previously specified, the result is implementation-defined, might not be correctly aligned, might not point to an entity of the referenced type, and might be a trap representation.

The subsequent pointer arithmetic:

ptr = (char *)ptr + 1; 

Is undefined behavior as per section 6.5.6:

8 When an expression that has integer type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the pointer operand points to an element of an array object, and the array is large enough, the result points to an element offset from the original element such that the difference of the subscripts of the resulting and original array elements equals the integer expression. In other words, if the expression P points to the i-th element of an array object, the expressions (P)+N (equivalently, N+(P) ) and (P)-N (where N has the value n ) point to, respectively, the i+n-th and i−n-th elements of the array object, provided they exist. Moreover, if the expression P points to the last element of an array object, the expression (P)+1 points one past the last element of the array object, and if the expression Q points one past the last element of an array object, the expression (Q)-1 points to the last element of the array object. If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined. If the result points one past the last element of the array object, it shall not be used as the operand of a unary * operator that is evaluated.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: