Consider a pointer char* p
that is not nullptr
, and the loop
while(++p);
Is the behaviour well defined or undefined? In other words, will the pointer eventually become 0 when reaching the maximum allocable memory (probably 2^32 or 2^64) or this is just UB?
std::numeric_limits is (as expected) not specialized for pointer types.
Faster and more efficient code can be written because pointers are closer to the hardware. That is, the compiler can more easily translate the operation into machine code. There is not as much overhead associated with pointers as might be present with other operators.
The pointer in C language is a variable which stores the address of another variable. This variable can be of type int, char, array, function, or any other pointer. The size of the pointer depends on the architecture. However, in 32-bit architecture the size of a pointer is 2 byte.
A pointer is simply a variable that holds the memory address of another type or variable. By default, C# does not allow you to use pointers in your apps.
To get the value pointed to by a pointer, you need to use the dereferencing operator * (e.g., if pNumber is a int pointer, *pNumber returns the value pointed to by pNumber . It is called dereferencing or indirection).
Short answer: by spec, it is undefined behavior. Performing any pointer arithmetic that leads to unallocated memory more than one address past an allocated item (see the One Past the End chapter in the GCC docs for the significance of this) is undefined behavior.
To see why, let us look at the standard:
Sec 3.7.4.3.2 in the C++11 standard enumerates over all "safely-derived pointer" types. Most items in sec 3.7.4.3.2 of the standard describe ways to obtain references to objects legally. Assuming a pointer refers to allocated memory, 3.7.4.3.2 simply states:
A pointer value is a safely-derived pointer to a dynamic object only if it has an object pointer type and it is one of the following:
- the result of well-defined pointer arithmetic (5.7) using a safely-derived pointer value;
Sec 5.7.4 states:
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 with the type of the object as its element type.
Finally, sec 5.7.5:
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.
From a specification point of view: it's UB.
From a what-will-it-do point of view, yes, it will eventually wrap around to zero in most environments, especially for plain C. It may take a century or so on a 64-bit system.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With