Re:Pitfalls in C and C++: Unsigned Types (2011)
by oleganza on Wednesday September 25, 2013 @02:46PM
(#6446470)
buf[-1] is equally incorrect as buf[4294967295], so int being signed or unsigned does not make any difference to the correctness of your loop.
[ Parent
| on HN ]
Re:Pitfalls in C and C++: Unsigned Types (2011)
by dllthomas on Wednesday September 25, 2013 @02:55PM
(#6446529)
Not so. buf[-1] will step on mapped memory that is probably something else important, and you won't find out about it until later, which is hard to debug and more likely disastrous (if there's room for disaster in the use of the software). buf[4294967295] will try to use memory that is almost certainly unmapped and unavailable, and will segfault immediately - right on the line that caused the problem - and won't take any potentially disastrous actions.
Re:Pitfalls in C and C++: Unsigned Types (2011)
by pslam on Wednesday September 25, 2013 @02:57PM
(#6446545)
buf[4294967295] is perfectly valid and expected on platforms where size_t is 64 bits and int is 32 bits. buf[-1] is almost always a bug, and would be useful to default (with overrides) as such.
Re:Pitfalls in C and C++: Unsigned Types (2011)
by dllthomas on Wednesday September 25, 2013 @03:13PM
(#6446644)
if buf[4295967295] is valid, then you should almost certainly be indexing with something bigger than 32 bits, and the max of your index is again likely to be invalid (and, as I've mentioned elsewhere, more usefully invalid than -1).
Re:Pitfalls in C and C++: Unsigned Types (2011)
by dllthomas on Thursday September 26, 2013 @03:14AM
(#6449349)
On reflection, using something larger doesn't help, since if sizeof(void*) == sizeof(i) then a[(__typeof(i))-1] will almost certainly refer to the same address whether i is signed or unsigned.