Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I take the address of one past the end of an array if the last address is 0xFFFFFFFF?

Tags:

c++

If it is legal to take the address one past the end of an array, how would I do this if the last element of array's address is 0xFFFFFFFF?

How would this code work:

for (vector<char>::iterator it = vector_.begin(), it != vector_.end(); ++it)
{
}

Edit:

I read here that it is legal before making this question: May I take the address of the one-past-the-end element of an array?

like image 802
Marlon Avatar asked Dec 04 '11 22:12

Marlon


3 Answers

If this situation is a problem for a particular architecture (it may or may not be), then the compiler and runtime can be expected to arrange that allocated arrays never end at 0xFFFFFFFF. If they were to fail to do this, and something breaks when an array does end there, then they would not conform to the C++ standard.

like image 60
Greg Hewgill Avatar answered Nov 04 '22 14:11

Greg Hewgill


Accessing out of the array boundaries is undefined behavior. You shouldn't be surprised if a demon flies out of your nose (or something like that)

What might actually happen would be an overflow in the address which could lead to you reading address zero and hence segmentation fault.

If you are always within the array range, and you do the last ++it which goes out of the array and you compare it against _vector.end(), then you are not really accessing anything and there should not be a problem.

like image 28
Shahbaz Avatar answered Nov 04 '22 14:11

Shahbaz


I think there is a good argument for suggesting that a conformant C implementation cannot allow an array to end at (e.g.) 0xFFFFFFFF.

Let p be a pointer to one-element-off-the-end-of-the-array: if buffer is declared as char buffer[BUFFSIZE], then p = buffer+BUFFSIZE, or p = &buffer[BUFFSIZE]. (The latter means the same thing, and its validity was made explicit in the C99 standard document.)

We then expect the ordinary rules of pointer comparison to work, since the initialization of p was an ordinary bit of pointer arithmetic. (You cannot compare arbitrary pointers in standard C, but you can compare them if they are both based in a single array, memory buffer, or struct.) But if buffer ended at 0xFFFFFFFF, then p would be 0x00000000, and we would have the unlikely situation that p < buffer!

This would break a lot of existing code which assumes that, in valid pointer arithmetic done relative to an array base, the intuitive address-ordering property holds.

like image 30
librik Avatar answered Nov 04 '22 12:11

librik