rust-lang / nomicon

The Dark Arts of Advanced and Unsafe Rust Programming
https://doc.rust-lang.org/nomicon/
Apache License 2.0
1.82k stars 262 forks source link

"9. Implementing Vec": Dangling pointer overflow? #433

Open kuzminrobin opened 10 months ago

kuzminrobin commented 10 months ago

I have an impression that in section 9.11. Final Code any fragment containing usize) + or usize + can overflow usize (equal to a dangling pointer), which will result in a panic in debug mode.

See also fragment of interest:

RawVec {
    ptr: NonNull::dangling(),

Details. The vector's buffer pointer is initialized to a dangling pointer value (so potentially the dangling buffer pointer can be close to overflowing).

For the zero-sized types the buffer is never allocated (the grow() is never called). So the buffer pointer stays dangling.

During the iterator creation the iterator's pointer RawValIter::end is initialized to the value ((slice.as_ptr() as usize) + slice.len()), where the fragment as usize) + can overflow the usize (equal to a dangling pointer); also the iterator's pointer RawValIter::start is initialized to the dangling pointer value (possibly close to overflowing), and during subsequent next() the fragment self.start as usize + 1 can overflow the usize.


Would be nice to see in the text of the book (e.g. in 9.11. Final Code)