I have a query about the behavior of C/C++ dealing with blindly incrementing a pointer.
So, I have a pointer to an int as a parameter to a function
func(int* thePointer) {...
and I have a loop inside that function
while(*thePointer) {
++thePointer;
}
I understand that as long as there are int's in the memory beyond this pointer the loop will continue, but what if the memory belongs to part of another memory type? Say you increment into the first 4 bytes of a double. Will the int still have a value/will the loop continue in this case?
Disclaimer: I know this is very most likely bad practice. This is a purely academic question.
In memory there is no such thing as a int or a double. Memory is just memory: placeholder for bytes.
So, if you keep incrementing a pointer to int, you will point to the next four bytes in memory and that's it. If you attempt to use that portion of the memory through the pointer to integer, you will probably treat its content as if it were an int.
Eventually, you will point to a region of the memory not being assigned to your process and your program will exit with a SEGMENTATION FAULT.
ISO 14882, section 5.7:
$4 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.
$5 When an expression that has integral 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 integral expression. In other words, if the expression P points to the ith 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+nth and i– nth 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 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