This is the mail archive of the
gcc-bugs@gcc.gnu.org
mailing list for the GCC project.
[Bug target/81801] [PATCH] Difference of two pointers generates signed overflow
- From: "joseph at codesourcery dot com" <gcc-bugzilla at gcc dot gnu dot org>
- To: gcc-bugs at gcc dot gnu dot org
- Date: Fri, 11 Aug 2017 12:18:54 +0000
- Subject: [Bug target/81801] [PATCH] Difference of two pointers generates signed overflow
- Auto-submitted: auto-generated
- References: <bug-81801-4@http.gcc.gnu.org/bugzilla/>
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=81801
--- Comment #4 from joseph at codesourcery dot com <joseph at codesourcery dot com> ---
On Fri, 11 Aug 2017, oss at malat dot biz wrote:
> One could solve it by dividing both pointers by the size before the
> subtraction, but that would make the operation more expensive.
See also what I said in bug 67999 comment 24.
The combination (subtract to produce a ptrdiff_t result, with modulo
arithmetic on overflow, then divide in ptrdiff_t) isn't correct for
objects too large in bytes for ptrdiff_t. But the following should be
correct: right shift (logical) both pointers for the power-of-2 factor in
what you are dividing by, subtract (modulo), multiply (modulo) by the (mod
2^n) reciprocal of the odd part of what you are dividing by, interpret the
result as signed.
It's less efficient than code sequences that only work for objects less
than half the address space, and such large objects can never work if you
do pointer subtraction of pointers to char that are too far apart to be
represented in ptrdiff_t. I think it makes most sense to disallow such
large objects properly (including in malloc and mmap), but an option to
support pointer subtraction in them would not be ridiculous.