Pointer undefined behaviors?

To my knowledge, the following are UB's (I'll give code below to be corrected if necessary):

1) dereferencing dangling/invalid pointer
2) going out of bounds, past the after-last element

1
2
3
4
5
6
7
int *pi = new int;
int *aux1 = pi + 1; // not UB
int *aux2 = pi + 2; // UB

*(pi + 1) = 5; // UB
delete pi;
*pi = 3; // UB 


My question: is it undefined behavior when we access a pointer pointing to a custom address?

For example, many OS development tutorials teach beginners to print to the screen by using a pointer set to 0xB8000.

Strictly speaking, that address isn't mapped to RAM but to the VGA memory, but still is this well-defined?
Last edited on
I've got no clue about the custom address answer but I was wondering how line two of your code isn't UB?
iHutch, it isn't allocated. whoops, I thought you meant line 3
@Catfish: It certainly isn't portable, and as such i'd say it is undefined behavior, because it isn't a language feature.
Last edited on
1
2
3
4
5
int *pi = new int;
int *aux1 = pi + 1; // not UB (corrected by Cubbi)

int* pi2 = new int[1] ;
int* aux2 = pi2 + 1; // not UB 

When an expression that has integral type is added to or subtracted from a pointer ...
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.


int* pi3 = reinterpret_cast<int*>(0xB8000) ; // implementation defined
A value of integral type or enumeration type can be explicitly converted to a pointer. A pointer converted to an integer of sufficient size (if any such exists on the implementation) and back to the same pointer type will have its original value; mappings between pointers and integers are otherwise implementation-defined.
Last edited on
int *aux1 = pi + 1; is not UB per one paragraph higher "For the purposes of these operators, a pointer to a nonarray object behaves the same as a pointer to the first element of an array of length one" -- this produces a pointer one past the end of this "array of length one"
Thanks, Cubbi.
Thanks for the replies, it did not occur to me that it may be "implementation defined", when it's obviously the way it should be.
Topic archived. No new replies allowed.