0

Hi I have this book with a practice question which I am unable to answer. And no...this is not a homework question. This is my self study from a book recommended to me called: "Computer systems, A programmer's perspective"

Here is the question: enter image description here

Any help is appreciated!

Mark Lakata
  • 19,989
  • 5
  • 106
  • 123
Krimson
  • 7,386
  • 11
  • 60
  • 97
  • Compiling this with `gcc -Wextra` would generate a warning for the comparison between signed (`int i`) and unsigned (`unsigned length`). – Jonathon Reinhart Oct 01 '13 at 03:55
  • Any reason you couldn't have just looked at the solution for this problem that the book provides for you? – Crowman Oct 01 '13 at 04:05
  • 1
    @JonathonReinhart warnings? Who has extra byte for that? [Real russian do push-up on bug](http://stackoverflow.com/a/652945/427309). – Richard J. Ross III Oct 01 '13 at 04:05

2 Answers2

11

length is unsigned, so if you pass 0 for that parameter, length - 1 will be UINT_MAX, not -1 like you want it to be; therefore the loop will run and you'll make acceses outside the size of a.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
  • 1
    @RichardJ.RossIII - overflow of unsigned integers is totally well defined. – Carl Norum Oct 01 '13 at 03:56
  • ohhhhhhhkay, I get it now! It wraps back around to all 1s. Thanks!, Sorry Im new these low level stuff :) – Krimson Oct 01 '13 at 03:57
  • 1
    Overflow of signed integers is *undefined*, but not unsigned types. – Carl Norum Oct 01 '13 at 03:58
  • 2
    Spec quotation: **6.2.5 Types** paragraph 9: "A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type." – Carl Norum Oct 01 '13 at 03:59
  • It's worth mentioning that seeing `i <= length-1` is pretty uncommon. While changing `length` from an unsigned integer to a signed integer is one solution, much more often you'll simply see the loop condition expressed as `i < length` (which is equivalent). This is "better," because negative array lengths are not possible, and the length parameter really *should* be unsigned, since that gives you the maximum possible range for your data type. – Matt Patenaude Oct 01 '13 at 05:07
1

Change this unsigned length to int length you code will run perfectly

while why the above code will not work is

when you use unsigned length if you pass 0 to the length so in the loop you have (length - 1) which is cycles over the range and it takes the maximum value hence the loop gets segmentation fault

Sohil Omer
  • 1,171
  • 7
  • 14